zoukankan      html  css  js  c++  java
  • 基于创建子进程(进程管理和通信的设计模型)

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

    // 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;
    }
  • 相关阅读:
    iptables 常用命令解析
    iptables 常用处理动作
    centos7 中iptables、firewalld 和 netfilter 的关系
    iptables 的几个状态
    centos7 中没有service iptables save指令来保存防火墙规则
    iptables 数据走向流程
    数据库PDO简介
    php连接mySql,加密函数
    php数组,常量,遍历等
    php的会话控制
  • 原文地址:https://www.cnblogs.com/yang131/p/13857757.html
Copyright © 2011-2022 走看看