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

本代码经过严格单元测试,如果谁能其中检测到代码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;
}

 

转载于:https://www.cnblogs.com/moiez/p/6000049.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值