代码:
这是来自更大的 MS 示例(http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx)。当然,我之前尝试过整个示例,我在下面的剪辑是我将其剥离到问题的地方。问题是如果我得到的只是1
. 如何发出没有更多数据要读取的信号?
(编译器是 MiGW。)
看起来 MS 示例已损坏,这是其中的评论之一:父进程需要关闭在 CreateProcess() 调用后传递给子进程的句柄。不这样做会导致父级在 ReadFile() 上永远等待。
#include <iostream>
#include <windows.h>
using namespace std;
int main() {
cout << "\n->Start of parent execution.\n";
SECURITY_ATTRIBUTES saAttr;
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0);
STARTUPINFO siStartInfo;
PROCESS_INFORMATION piProcInfo;
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
CreateProcess(NULL,
(char*)"cmd /c dir", // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
CHAR chBuf[4096];
DWORD dwRead;
// ~~~~~~this loop here~~~~~- how to break out of it ?
while(true) {
cout << "ReadFile: " << ReadFile( g_hChildStd_OUT_Rd, chBuf, 4096, &dwRead, NULL) << endl;
}
cout << "\n->End of parent execution.\n";
}