首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

快崩溃了,匿名管道通信,为啥子进程总是读不到管道中的数据?解决方案

2012-05-28 
快崩溃了,匿名管道通信,为啥子进程总是读不到管道中的数据?控制台程序,在父进程中创建匿名管道,把管道读句

快崩溃了,匿名管道通信,为啥子进程总是读不到管道中的数据?
控制台程序,在父进程中创建匿名管道,把管道读句柄传递给子进程。子进程是另一个控制台应用程序。

搞了好久还是没搞定。我看了一下我的代码,实在想不出为什么。

只是父进程代码,父进程只需向子进程说“hello”

C/C++ code
#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;}


这是子进程,子进程读取父进程说的话并打印出来。
C/C++ code
#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;}


[解决办法]
HANDLE hReadPipe = si.hStdInput; 
输出流重定向了,当然控制台上看不到了。
[解决办法]
SetStdHandle 和 GetStdHandle

C/C++ code
BOOL SetStdHandle(  DWORD nStdHandle,  // input, output, or error device  HANDLE hHandle     // handle to be a standard handle);
[解决办法]
探讨

我是通过父进程定向了子进程的标准输入定向到了管道。。现在想把标准输入重新定向到控制台。
引用:

SetStdHandle 和 GetStdHandle

C/C++ code

BOOL SetStdHandle(
DWORD nStdHandle, // input, output, or error device
HANDLE hHandle ……

热点排行