gpt4 book ai didi

winapi - 从管道读取时 Win32 ReadFile 挂起

转载 作者:行者123 更新时间:2023-12-04 13:28:08 24 4
gpt4 key购买 nike

我正在创建一个子进程,并读取其输出。当子进程创建输出( cmd /c echo Hello World )时,我的代码工作正常,但是如果进程不创建输出( cmd /c echo Hello World > output.txt ), ReadFile 将挂起。我只是在进程终止后阅读。

我做错了什么吗?无论如何要使用同步模式来做到这一点,还是我必须使用异步模式?所有这一切都发生在一个单独的线程中,所以我认为异步模式不会给我带来任何好处,除非这是让它工作的唯一方法。非常感谢!

saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;

CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0);
SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0);

memset(&piProcInfo, 0, sizeof(PROCESS_INFORMATION));
memset(&siStartInfo, 0, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
CreateProcess(NULL, commandWideString, NULL, NULL, TRUE, 0, NULL, NULL, &siStartInfo, &piProcInfo);

while(1)
{
GetExitCodeProcess(piProcInfo.hProcess, &processExitCode);
if(processExitCode != STILL_ACTIVE)
break;
else
Sleep(1);
}

*output = (char *)calloc(32, sizeof(char));
processOutputSize = 0;
while(1)
{
bSuccess = ReadFile( g_hChildStd_OUT_Rd, processOutputTemp, 32, &dwRead, NULL);
if(!bSuccess || !dwRead)
break;
memcpy(*output + processOutputSize, processOutputTemp, dwRead);
processOutputSize += dwRead;
if(dwRead == 32)
*output = (char *)realloc(*output, processOutputSize + 32);
else
{
memset(*output + processOutputSize, 0, 1);
break;
}
}
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
CloseHandle(g_hChildStd_OUT_Rd);
CloseHandle(g_hChildStd_OUT_Wr);

最佳答案

正如@Marcus 在评论中建议的那样,您应该在读取之前关闭输出管道的写入端。
CloseHandle(g_hChildStd_OUT_Wr);
对我来说,这才是真正的答案。

关于winapi - 从管道读取时 Win32 ReadFile 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13816962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com