首页 > 系统服务 > 详细

基于创建子进程(进程管理和通信的设计模型)

时间:2020-10-22 14:33:13      阅读:37      评论:0      收藏:0      [点我收藏+]

通过创建管道,捕获子进程(控制台进程)的输入和输出

// Console.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <Windows.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

string invoke(string exe);

int main(int argc, char* argv[])
{
    string exe = "Caculate.exe";
    cout << invoke(exe) << endl;

    return 0;
}


string invoke(string exe)
{
    string output;
    SECURITY_ATTRIBUTES saPipe;
    saPipe.nLength = sizeof(SECURITY_ATTRIBUTES);
    saPipe.lpSecurityDescriptor = NULL;
    saPipe.bInheritHandle = TRUE;

    HANDLE hReadPipe, hWritePipe;
    BOOL bSuccess = CreatePipe(&hReadPipe,
        &hWritePipe,
        &saPipe,
        0);
    if (!bSuccess)
        return output;

    PROCESS_INFORMATION pi;
    STARTUPINFOA si;
    memset(&si, 0, sizeof(si));
    si.hStdInput = hReadPipe;
    si.hStdOutput = hWritePipe;
    si.dwFlags = STARTF_USESTDHANDLES;
    si.cb = sizeof(si);
    char ch[1024];
    strcpy_s(ch, "Caculate + 12.2 23.3");

    //if (CreateProcessA(exe.c_str(), ch, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
    if (CreateProcessA(NULL, ch, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
    {
        const int max = 2048;
        char buf[max] = { 0 };
        DWORD dw;
        if (ReadFile(hReadPipe, buf, max - 1, &dw, NULL))
        {
            output = buf;
            //            ZeroMemory(buf,max);
            //cin >> buf;
            //WriteFile(hWritePipe, buf, max - 1, &dw, NULL);
        }
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
    }
    else {
        SetStdHandle(STD_INPUT_HANDLE, hWritePipe);
        SetStdHandle(STD_OUTPUT_HANDLE, hReadPipe);
    }

    CloseHandle(hReadPipe);
    CloseHandle(hWritePipe);
    return output;
}

 

基于创建子进程(进程管理和通信的设计模型)

原文:https://www.cnblogs.com/yang131/p/13857757.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!