Windows CreateProcess和输出重定向

时间:2016-03-16 11:31:59

标签: c windows io-redirection createprocess

我正在使用WinAPI在C项目,Windows环境中工作。 我的函数执行它作为参数接收的命令(e.g. : "dir C:\Users"),并返回其输出 它是从DLL运行的,所以它不能产生cmd.exe窗口,这意味着我不能使用_popen。所以我使用CreateProcessA和一个管道来捕获标准输出。

以下是代码:

char *runExec(char *command, int *contentLen) {
    char *ret=NULL,*tmp=NULL;
    DWORD readBytes;
    int size=0;
    char buffer[128],cmdBuf[4096];
    HANDLE StdOutHandles[2];

    CreatePipe(&StdOutHandles[0], &StdOutHandles[1], NULL, 4096);

    STARTUPINFOA si;   
    memset(&si, 0, sizeof(si));
    si.cb = sizeof(si);
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.wShowWindow = SW_HIDE;
    si.hStdOutput = StdOutHandles[1];
    si.hStdError = StdOutHandles[1];
    PROCESS_INFORMATION pi;

    snprintf(cmdBuf,4096,"cmd /C %s", command);
    if (!CreateProcessA(NULL, cmdBuf, NULL, NULL, FALSE, CREATE_NO_WINDOW | DETACHED_PROCESS, NULL, NULL, &si, &pi)) {
        printf("Error createProcess : %d\n",GetLastError());
        return NULL;
    }


    CloseHandle(StdOutHandles[1]);
    printf("Before read\n");
    while (ReadFile(StdOutHandles[0], buffer, 127, &readBytes, NULL)){
        printf("IN WHILE\n");
        buffer[readBytes] = 0;
        printf("read %d bytes\n", readBytes);
        size += readBytes;
        tmp = (char *)realloc(ret, size + 1);
        if (tmp == NULL) {
            free(ret);
            return NULL;
        }
        ret = tmp;
        strncpy(ret + (size - readBytes), buffer, readBytes);
        ret[size] = 0;
    }
    printf("Readfile returned with %d, read %d\n", GetLastError(),readBytes);

    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    CloseHandle(StdOutHandles[0]);
    printf("#%s#\n", ret);

    return ret;
}

输出结果为:

Before read
Readfile returned with 109, read 0
#(null)#

因此我理解:
  - 我的循环甚至没有执行一次   - ReadFile不读任何内容并立即返回Broken Pipe

我已阅读各种stackoverflow和MSDN页面,但我似乎无法使其正常工作。

1 个答案:

答案 0 :(得分:0)

正如评论中所指出的,句柄必须是可继承的,这意味着像这样替换CreatePipe

SECURITY_ATTRIBUTES pipeAttrib;
memset(&pipeAttrib, 0, sizeof(pipeAttrib));

pipeAttrib.nLength = sizeof(SECURITY_ATTRIBUTES);
pipeAttrib.bInheritHandle = NULL;
pipeAttrib.bInheritHandle = TRUE;

if (!CreatePipe(&StdOutHandles[0], &StdOutHandles[1],&pipeAttrib, 4096)) {
    printf("Create pipe error %d\n", GetLastError());
    return NULL;
}

CreateProcess第五个参数(bInheritHandles)设置为TRUE而不是FALSE