管道问题
新手,还请大家多关照
下面是一个匿名管道的例子,看了以后有几个问题:
1.关于DuplicateHandle函数。
这里为什么要创建一个副本,对于DuplicateHandle函数的用法还是不甚明了,还请大侠指教!
2.关于STD_INPUT_HANDLE,STD_OUTPUT_HANDLE。
#include "stdafx.h"
#include "windows.h"
#include "winbase.h"
#include "iostream.h"
int main(int argc, char* argv[])
{
HANDLE hProcess;
HANDLE hwrite;
HANDLE hread;
int i;
BOOL bTest;
DWORD dwWritten;
SECURITY_ATTRIBUTES sa;
STARTUPINFO sui; //子进程窗口属性结构
PROCESS_INFORMATION pi; //子进程信息
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
bTest = CreatePipe(&hread, &hwrite, &sa, 0);
if(!bTest)
{
cout<<"create pipe error"<<endl;
return -1;
}
bTest=DuplicateHandle(GetCurrentProcess(),
hwrite, GetCurrentProcess(),
NULL,0,FALSE,DUPLICATE_SAME_ACCESS);
if(!bTest){
cout<<"Dup Handle failed!"<<endl;
CloseHandle(hread);
CloseHandle(hwrite);
return -1;
}
memset(&sui,0, sizeof(STARTUPINFO));
sui.cb = sizeof(STARTUPINFO);
sui.dwFlags = STARTF_USESTDHANDLES;
sui.hStdInput = hread;
sui.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
sui.hStdError = GetStdHandle(STD_ERROR_HANDLE);
bTest = CreateProcess(NULL, "child.exe",NULL,NULL,TRUE,NULL,NULL,
NULL,&sui, &pi);
if(!bTest)
{
cout<<"create process failed"<<endl;
CloseHandle(hwrite);
CloseHandle(hread);
return -1;
}
else
{
hProcess = pi.hProcess;
CloseHandle(pi.hThread);
i = 100;
while(1)
{
bTest = WriteFile(hwrite, &i, sizeof (int),&dwWritten, NULL);
if(!bTest)
{
cout<<GetLastError()<<endl;
return -1;
}
Sleep(1000);
}
}
return 0;
}