簡體   English   中英

子進程退出后,匿名管道的ReadFile不返回

[英]ReadFile from anonymous pipe doesn't return after the child process exited

我正在嘗試獲取子進程的輸出並進行解析。

這是我的代碼:

    DWORD Invoker::InvokeAndOutput() {
    wchar_t *cmd_line = _wcsdup(command_line.c_str());
    wchar_t *cwd_path = _wcsdup(cwd.c_str());

    HANDLE pipe_read , pipe_write;

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

    CreatePipe(&pipe_read,&pipe_write,&saAttr,0);

    SetHandleInformation(pipe_read,HANDLE_FLAG_INHERIT,0);

    STARTUPINFOW startup_info = {0};
    startup_info.cb = sizeof(startup_info);
    startup_info.hStdOutput = pipe_write;
    startup_info.dwFlags |= STARTF_USESTDHANDLES;
    PROCESS_INFORMATION proc_info = {0};

    CreateProcessW(0,cmd_line,0,0,TRUE,0,0,cwd_path,&startup_info,&proc_info);
    char buffer[1000] = {0};
    BOOL result;
    DWORD read;
    while(1) {
        memset(buffer,0,1000);
        result = ReadFile(pipe_read,buffer,1000,&read,0);
        if (!result || !read) break; // the execution doesn't get here after the child process exited
        else MessageBoxA(0,buffer,0,0);
    }
    WaitForSingleObject(proc_info.hProcess,INFINITE);
    DWORD exit_code;
    if (!GetExitCodeProcess(proc_info.hProcess,&exit_code)) return -1;
    return exit_code;
}

我在某些問題中看到需要在父進程中關閉管道的句柄,因此我嘗試了以下操作:

CreateProcessW(0,cmd_line,0,0,TRUE,0,0,cwd_path,&startup_info,&proc_info);
CloseHandle(pipe_read);

但是現在我無法從子進程中獲取輸出。

任何幫助都將受到歡迎。

問題解決了,我只需要關閉寫端

CreateProcessW(0,cmd_line,0,0,TRUE,0,0,cwd_path,&startup_info,&proc_info);
//CloseHandle(pipe_read);
CloseHandle(pipe_write);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM