通过创建管道,捕获子进程(控制台进程)的输入和输出
// 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; }