1. 程式人生 > 實用技巧 >基於建立子程序(程序管理和通訊的設計模型)

基於建立子程序(程序管理和通訊的設計模型)

通過建立管道,捕獲子程序(控制檯程序)的輸入和輸出

// 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; }