请问读管道时,为什么进入ReadFile后就没有响应了?
通过调试看到已经有控制台输出了,命令是 ping 192.168.3.142
HANDLE hRead;
HANDLE hWrite;
SECURITY_ATTRIBUTES sa; //安全结构体,决定子进程是否可被继承
sa.bInheritHandle=TRUE;
sa.lpSecurityDescriptor=NULL;
sa.nLength=sizeof(_SECURITY_ATTRIBUTES);
if(!CreatePipe(&hRead,&hWrite,&sa,0))
{
//创建匿名管道失败,线程结束。
return;
}
CString temp;
InputBox.GetWindowText(temp);
//MessageBox(temp);
//WCHAR * pParm = (char *)malloc(50);// L"ping 192.168.3.142";
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
si.dwFlags = si.dwFlags|STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOW;//SW_HIDE;
si.hStdInput=hRead;
si.hStdOutput=hWrite;
if( !CreateProcess( NULL, // No module name (use command line).
temp.GetBuffer(), // Command line.
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
0, // No creation flags. CREATE_NO_WINDOW
NULL, // Use parent's environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi ) // Pointer to PROCESS_INFORMATION structure.
)
{
MessageBox(0);
}
// char MAX[4096];
// memset(MAX,0,4096);
// DWORD dwRead;
// if(ReadFile(hRead,MAX,100,&dwRead,NULL)==NULL)
// {
// //读取失败退出程序
//
// return ;
// }
//Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
char MAX[4096];
DWORD dwRead;
memset(MAX,0,4096);
if(ReadFile(hRead,MAX,100,&dwRead,NULL)==NULL)
{
//读取失败退出程序
return ;
}
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
------解决思路----------------------
1. si.dwFlags 中加上 STARTF_USESTDHANDLES
2. CreateProcess 的第 5 个参数改成 TURE