c++ pipe实现父子进程通信

1、父子进程通信pipe编程流程

-创建管道

-设置进程的输出到管道

-创建进程

-关闭管道写句柄

-读管道读句柄,把数据读到一个buffer

2、注意事项

-读管道数据的时候,一定要关闭写句柄;

-父子进程通信时,句柄的传递多通过继承来完成,父进程允许这些句柄为子进程继承;创建子进程,是否继承的属性要设置为true

 // pdfprintconsole.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h" #include <iostream> #include <Windows.h> #include<tchar.h> #include <string.h> int main() { int page_index = 0; char currentBuff[1000] = { 0 }; char cachFileName[1000] = { 0 }; char printCommand[1000] = { 0 }; char command[500] = { 0 }; HANDLE handle = 0; BOOL bTest = 0; SECURITY_ATTRIBUTES sa = { 0 }; DWORD dwNumberOfBytesRead = 0; CHAR szBuffer[10000] = { 0 }; DWORD ret = 0; HANDLE hPipeOutputRead = NULL; HANDLE hPipeOutputWrite = NULL; STARTUPINFOA si = { 0 }; PROCESS_INFORMATION pi = { 0 }; sa.bInheritHandle = TRUE; // TRUE为管道可以被子进程所继承 sa.lpSecurityDescriptor = NULL; // 默认为NULL sa.nLength = sizeof(SECURITY_ATTRIBUTES); // Create pipe for standard output redirection. CreatePipe(&hPipeOutputRead, // read handle &hPipeOutputWrite, // write handle &sa, // security attributes 0 // number of bytes reserved for pipe - 0 default  ); // Make child process use hPipeOutputWrite as standard out, // and make sure it does not show on screen. si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.wShowWindow = SW_HIDE; //si.hStdInput = hPipeInputRead; si.hStdOutput = hPipeOutputWrite; si.hStdError = hPipeOutputWrite; //strcpy_s(command, " -printer \"FX DocuCentre S2011\" -paper 9 -printermargins C:\\Users\\QJ\\Desktop\\f3044688ce88a4b0a78c16ba85076570-5378-0010-0.png"); strcpy_s(command," -printer \"FX DocuCentre S2011\" -listpapers"); //一共执行三次 for (int i = 0; i < 3; i++) { if (!CreateProcessA("C:\\Users\\QJ\\source\\repos\\WindowsFormsApp1\\x64\\Debug\\pdfprint.exe", command, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) { //AfxMessageBox("缺失pdfprint.exe文件",0,0); break; } else { HANDLE hProcess = pi.hProcess; //等待进程退出 //CloseHandle(hPipeOutputRead); while (WaitForSingleObject(hProcess, INFINITE) != WAIT_OBJECT_0); GetExitCodeProcess(hProcess, &ret); //如果ret!=0,异常退出; //  CloseHandle(hPipeOutputWrite); while (true) { bTest = ReadFile( hPipeOutputRead, // handle of the read end of our pipe &szBuffer, // address of buffer that receives data sizeof(szBuffer), // number of bytes to read &dwNumberOfBytesRead, // address of number of bytes read NULL // non-overlapped.  ); if (!bTest) { break; } // do something with data. szBuffer[dwNumberOfBytesRead] = 0; // null terminate  } if (!ret) { printf("123%s456\nbtest:%d\n", szBuffer, bTest); CloseHandle(hProcess); CloseHandle(hPipeOutputRead); break; } } } //std::cout << "Hello World!\n"; system("pause"); }

猜你喜欢

转载自www.cnblogs.com/freedomworld/p/11703447.html