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


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

    // 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;
    }
  • 相关阅读:
    js 实现加入收藏/加入首页功能
    js 获取网页宽/高度
    js 飞机大战
    js 实现分享功能
    前端开发的工具,库和资源总结
    网站更新后客户端缓存问题
    js 实现图片无限横向滚动效果
    js 实现 文字打印效果
    js 构造函数创建钟表
    Css3 实现关键帧动画
  • 原文地址:https://www.cnblogs.com/yang131/p/13857757.html
Copyright © 2020-2023  润新知