匿名管道实现获取控制台程序输出

本代码经过严格单元测试,如果谁能其中检测到代码bug,我请他一杯最好喝的咖啡!☕️

 

#define EXECDOSCMD "dir c:" //可以换成你的命令
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <time.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h>
#include <process.h>
#include <string>
#include <windows.h>

int main()
{
    HANDLE hRead, hWrite;

    SECURITY_ATTRIBUTES securityAttr;
    securityAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    securityAttr.lpSecurityDescriptor = NULL;
    securityAttr.bInheritHandle = TRUE;
    if (CreatePipe(&hRead, &hWrite, &securityAttr, 0) == 0) {
        printf("ERROR!! CreatePipe()=[0]. GetLastError()=[%d].\n", GetLastError());
        return FALSE;
    }

    STARTUPINFO            startupInfo;
    PROCESS_INFORMATION processInfo;
    DWORD dwRetVal = 0;
    startupInfo.cb = sizeof(STARTUPINFO);
    GetStartupInfo(&startupInfo);
    startupInfo.hStdError = hWrite;            //把创建进程的标准错误输出重定向到管道输入 
    startupInfo.hStdOutput = hWrite;           //把创建进程的标准输出重定向到管道输入 
    startupInfo.wShowWindow = SW_HIDE;
    startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

    char szCmdLine[1024];
    sprintf(szCmdLine, "cmd.exe /C %s", EXECDOSCMD);

    if (CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, NULL, NULL, NULL, &startupInfo, &processInfo) == 0) {
        printf("ERROR!! CreateProcess()=[0]. GetLastError()=[%d].\n", GetLastError());
        CloseHandle(hWrite);
        CloseHandle(hRead);
        return FALSE;
    }
    else {
        WaitForSingleObject(processInfo.hProcess, INFINITE);

        if (GetExitCodeProcess(processInfo.hProcess, &dwRetVal) == 0) {
            printf("ERROR!! GetExitCodeProcess()=[0]. GetLastError()=[%d].\n", GetLastError());
        }
        else {
            printf("The command runs successfully with returns code: [%d].\n", dwRetVal);
        }
    }
    CloseHandle(processInfo.hThread);
    CloseHandle(processInfo.hProcess);
    CloseHandle(hWrite);

    char szOutputBuffer[4096]; 
    DWORD dwBytesRead;
    while (true) {
        memset(szOutputBuffer, 0x00, sizeof(szOutputBuffer));
        if (ReadFile(hRead, szOutputBuffer, 4095, &dwBytesRead, NULL) == FALSE)
            break;

        printf("result = [%s]\n", szOutputBuffer);
    }
    CloseHandle(hRead);

    return TRUE;
}

 

posted @ 2016-10-26 13:36  天体风雪  阅读(1140)  评论(3编辑  收藏  举报