[英]ReadFile hanging on pipe reading
我正在使用CreateProcess()
來運行cmd.exe
(沒有向用戶顯示物理窗口)並需要處理輸出。 我已決定使用CreatePipe()
來實現此目的。
我目前遇到一個問題,即我的所有輸出都被讀取和處理,但最后調用ReadFile()
是掛起的。 搜索周圍告訴我,我需要在閱讀之前關閉管道的寫入側,這是解決這個問題的方法,但我已經完成了這個並且仍然有問題。
這是我的代碼:
// sw -> path to cmd.exe, ptr is the command
ok = CreateProcess(sw, ptr, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &StartupInfo, &ProcessInfo);
CloseHandle(hStdInPipeRead);
char buf[1024 + 1] = {};
DWORD dwRead = 0;
DWORD dwAvailable = 0;
DWORD testRes;
CloseHandle(hStdOutPipeWrite);
ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
// String handling for initial read omitted for clarity
string temp = buf;
bool holdOff = false;
while (ok == TRUE)
{
buf[dwRead] = '\0';
OutputDebugStringA(buf);
puts(buf);
// ReadFile gets all the correct output from cmd here but it also hangs on the very last call. How to fix?
ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
temp = buf;
// handle and store output
break;
}
CloseHandle(hStdOutPipeRead);
CloseHandle(hStdInPipeWrite);
如果你設置SECURITY_ATTRIBUTES.bInheritHandle = true
,子進程將繼承管道的句柄,你關閉的管道的寫句柄只是父進程,子進程中仍然有一個句柄(子進程的stdout),它沒有在cihld進程中已關閉, Readfile
失敗並僅在所有寫入句柄關閉或發生錯誤時返回。
此外, 匿名管道運營 。
匿名管道(
CreatePipe
創建)不支持異步(重疊)讀取和寫入操作。
因此,如果您仍需要向子進程發送命令以執行cmd,則應將ReadFile
放入線程中。 如果您不再需要,請終止子進程:
TerminateProcess(ProcessInfo.hProcess,0);
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
// String handling for initial read omitted for clarity
string temp = buf;
bool holdOff = false;
while (ok == TRUE)
{
buf[dwRead] = '\0';
OutputDebugStringA(buf);
puts(buf);
// ReadFile gets all the correct output from cmd here but it also hangs on the very last call. How to fix?
ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
temp = buf;
// handle and store output
break;
}
CloseHandle(hStdOutPipeRead);
CloseHandle(hStdInPipeWrite);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.