【问题标题】:ReadFile from anonymous pipe doesn't return after the child process exited子进程退出后,来自匿名管道的 ReadFile 不返回
【发布时间】:2018-07-20 16:33:02
【问题描述】:

我正在尝试获取子进程的输出并对其进行解析。

这是我的代码:

    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);

但现在我无法从子进程中获取输出。

欢迎任何帮助。

【问题讨论】:

    标签: c++ process pipe readfile


    【解决方案1】:

    问题解决了,我只需要关闭写端

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

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多