參考網址:http://www.xuebuyuan.com/1959215.htmlhtml
個人測試代碼:ios
Pipe_Server_VC6_Console.exe :windows
1 #include <windows.h> 2 3 #include <iostream> 4 using namespace std; 5 6 int main() 7 { 8 //定義四個句炳保留兩個管道的信息 9 HANDLE hReadPipe1, hWritePipe1, hReadPipe2, hWritePipe2; 10 SECURITY_ATTRIBUTES sat; 11 STARTUPINFO startupinfo; 12 PROCESS_INFORMATION pinfo; 13 BYTE buffer[1024]; 14 DWORD byteRead, byteWrite; 15 16 string rString; 17 string m_Host= "Pipe_Client_VC6_Console.exe"; 18 19 sat.nLength=sizeof(SECURITY_ATTRIBUTES); 20 sat.bInheritHandle=true; 21 sat.lpSecurityDescriptor=NULL; 22 23 //建立管道,它用來作子進程的輸出 24 if(!CreatePipe(&hReadPipe1, &hWritePipe1, &sat, NULL)) 25 { 26 cout<<("Create Pipe Error!")<<endl; 27 return 1; 28 } 29 30 //建立管道,它用來作子進程的輸入 31 if(!CreatePipe(&hReadPipe2, &hWritePipe2, &sat, NULL)) 32 { 33 cout<<"Create Pipe Error!"<<endl; 34 return 1; 35 } 36 37 startupinfo.cb=sizeof(STARTUPINFO); 38 //用GetStartupInfo得到當前進程的參數,不然STARTUPINFO參數太多,會讓人抓狂 39 GetStartupInfo(&startupinfo); 40 startupinfo.hStdInput = hReadPipe2; 41 startupinfo.hStdError=hWritePipe1; 42 startupinfo.hStdOutput=hWritePipe1; 43 //要有STARTF_USESTDHANDLES,不然hStdInput, hStdOutput, hStdError無效 44 startupinfo.dwFlags=STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; 45 startupinfo.wShowWindow=SW_HIDE; 46 if(!CreateProcess(NULL, (char*)m_Host.c_str(), NULL, NULL, TRUE, NULL, NULL, NULL, &startupinfo, &pinfo)) 47 { 48 cout<<("create process error!")<<endl; 49 return 1; 50 } 51 52 RtlZeroMemory(buffer,1024); 53 //進程的輸出重定向到hWritePipe1,因此從hReadPipe1讀取 54 // 在從管道中讀取到數據前父進程將發生阻塞 55 if (ReadFile(hReadPipe1,buffer,1023,&byteRead,NULL)) 56 { 57 cout<<buffer; 58 } 59 60 string csWrite = "ping www.sina.com.cn\r\n"; 61 //進程的輸入重定向到hReadPipe2,因此從hWritePipe2寫入 62 // 向管道中寫數據不會發生阻塞,此循環會一直執行下去。 63 while (WriteFile(hWritePipe2, (LPCVOID)csWrite.c_str(), csWrite.length() + 1, &byteWrite, NULL)) 64 { 65 Sleep(1000); 66 cout << "write " << byteWrite << endl; 67 } 68 69 70 CloseHandle(hReadPipe1); 71 CloseHandle(hReadPipe2); 72 CloseHandle(hWritePipe1); 73 CloseHandle(hWritePipe2); 74 75 return 0; 76 }
Pipe_Client_VC6_Console.exe :測試
1 #include <windows.h> 2 3 #include <iostream> 4 using namespace std; 5 6 int main(int argc, char* argv[]) 7 { 8 HANDLE hRead = GetStdHandle(STD_INPUT_HANDLE); 9 HANDLE hWrite = GetStdHandle(STD_OUTPUT_HANDLE); 10 11 char s[] = "Hello, I am child process\n"; 12 DWORD dwWrite; 13 14 if (!WriteFile(hWrite, s, strlen(s) + 1, &dwWrite, NULL)) 15 { 16 cout << "Write to pipe failed!" << endl; 17 return -1; 18 } 19 20 char buf[100]; 21 DWORD dwRead; 22 if(!ReadFile(hRead, buf, 100, &dwRead, NULL)) 23 { 24 cout << "Read from pipe failed!" << endl; 25 return -1; 26 } 27 28 return 0; 29 }
Cspa