快崩溃了,匿名管道通信,为啥子进程总是读不到管道中的数据?
控制台程序,在父进程中创建匿名管道,把管道读句柄传递给子进程。子进程是另一个控制台应用程序。
搞了好久还是没搞定。我看了一下我的代码,实在想不出为什么。
只是父进程代码,父进程只需向子进程说“hello”
#include <IOSTREAM>#include <windows.h>using namespace std;int main(void){ HANDLE hReadPipe,hWritePipe; SECURITY_ATTRIBUTES SA; SA.nLength = sizeof(SECURITY_ATTRIBUTES); SA.lpSecurityDescriptor = NULL; SA.bInheritHandle = TRUE; if (!CreatePipe(&hReadPipe,&hWritePipe,&SA,0)) { cout<<"error! cannot create pipe!\n"; cout<<GetLastError()<<endl; return 0; } STARTUPINFO si; PROCESS_INFORMATION pi; si.cb = sizeof(STARTUPINFO); GetStartupInfo(&si); si.hStdInput = hReadPipe;// si.hStdOutput = hWritePipe;// si.hStdError = hWritePipe; si.dwFlags = STARTF_USESTDHANDLES; char title[]="child"; si.lpTitle = title; if(!CreateProcess("childprocess.exe",NULL,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)) { cout<<"error! cannot create child process\n"; cout<<GetLastError()<<endl; return 0; } DWORD bytewrite; char str[20]="hello"; WriteFile(hWritePipe,str,strlen(str)+1,&bytewrite,NULL); cout<<bytewrite<<str<<endl; CloseHandle(pi.hProcess); CloseHandle(pi.hThread); WaitForSingleObject(pi.hProcess,INFINITE); return 0;}#include <iostream>#include "windows.h"using namespace std ;int main(){ // HANDLE hReadPipe = GetStdHandle(STD_INPUT_HANDLE);// HANDLE hReadPipe = si.hStdInput; STARTUPINFO si = { sizeof(si) }; GetStartupInfo(&si); HANDLE hReadPipe = si.hStdInput; DWORD bytewrite; char str[30]; ReadFile(hReadPipe,str,20,&bytewrite,NULL); cout<<str<<endl; return 0;}BOOL SetStdHandle( DWORD nStdHandle, // input, output, or error device HANDLE hHandle // handle to be a standard handle);
[解决办法]