在写Online Judge时,使用pipe来获得编译的输出结果。
在使用ReadFile读管道时,当结果全部读完后,在调用ReadFile竟然一直阻塞,这着实让我纳闷了一阵。
反复试验后,发现在关闭hWritePipe后,函数读完就立即返回。
到晚上一查:
The ReadFile function returns when one of the following conditions occur:
A write operation completes on the write end of the pipe.
The number of bytes requested is read.
An error occurs.
果然还是csdn没有理解透,先前我也考到这段文字,但是没有真正理解“A write operation completes on the write end of the pipe",看来,只有把hWritePipe关闭后,写操作才算完成。
贴出部分代码:
HANDLE hReadPipe,
hWritePipe;
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
bRet = CreatePipe(&hReadPipe, &hWritePipe, &sa, 1024);
if(!bRet)
{
debug("Create compiler pipe error:%X/n", GetLastError());
return E_COMPILER_COF;
}
// Compiler process StarupInfo
STARTUPINFO StartupInfo;
GetStartupInfo(&StartupInfo);
StartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
StartupInfo.wShowWindow = SW_HIDE;
StartupInfo.cb = sizeof(STARTUPINFO);
StartupInfo.hStdOutput = hWritePipe;
StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
StartupInfo.hStdError = hWritePipe;
char* ptr = strrchr(szCodePath, '//');
if(ptr)
{
char* it = szCodePath;
while(it != ptr && *it != '/0 ')
{
*(szCurrentDirectory + (int)(it - szCodePath)) = *it;
it ++;
}
debug("CurrentDirectory:%s/n", szCurrentDirectory);
SetCurrentDirectory((LPCSTR)szCurrentDirectory);
}
PROCESS_INFORMATION ProcessInfo;
bRet = CreateProcess(NULL, (LPTSTR)pCmd, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInfo);
if(!bRet)
{
return E_COMPILER_CP;
}
DWORD dwExitCode;
DWORD dwRet = WaitForSingleObject(ProcessInfo.hProcess, Settings::dwWaitForComipilerTime);
if(dwRet != WAIT_OBJECT_0 && !GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode))
{
if(dwRet == WAIT_TIMEOUT)
{
return E_COMPILER_TO;
}
return E_COMPILER_RF;
}
debug("Compiler exit code: %d", dwExitCode);
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
CloseHandle(hWritePipe); //A write operation completes on the write end of the pipe.
char buffer[1024] = {0};
DWORD dwRead;
while(ReadFile(hReadPipe, (LPVOID)buffer, sizeof(buffer) - 1, &dwRead, NULL) && dwRead > 0)
{
printf(buffer);
memset(buffer, 0, sizeof(buffer));
}
if(dwExitCode == E_UNKNOWN)
{
return E_COMPILER_CE;
}
CloseHandle(hReadPipe);