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"); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM