匿名管道实现获取控制台程序输出
生活随笔
收集整理的這篇文章主要介紹了
匿名管道实现获取控制台程序输出
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
本代碼經(jīng)過(guò)嚴(yán)格單元測(cè)試,如果誰(shuí)能其中檢測(cè)到代碼bug,我請(qǐng)他一杯最好喝的咖啡!??
?
#define EXECDOSCMD "dir c:" //可以換成你的命令 #define _CRT_SECURE_NO_WARNINGS#include <stdio.h> #include <time.h> #include <memory.h> #include <stdlib.h> #include <string.h> #include <process.h> #include <string> #include <windows.h>int main() {HANDLE hRead, hWrite;SECURITY_ATTRIBUTES securityAttr;securityAttr.nLength = sizeof(SECURITY_ATTRIBUTES);securityAttr.lpSecurityDescriptor = NULL;securityAttr.bInheritHandle = TRUE;if (CreatePipe(&hRead, &hWrite, &securityAttr, 0) == 0) {printf("ERROR!! CreatePipe()=[0]. GetLastError()=[%d].\n", GetLastError());return FALSE;}STARTUPINFO startupInfo;PROCESS_INFORMATION processInfo;DWORD dwRetVal = 0;startupInfo.cb = sizeof(STARTUPINFO);GetStartupInfo(&startupInfo);startupInfo.hStdError = hWrite; //把創(chuàng)建進(jìn)程的標(biāo)準(zhǔn)錯(cuò)誤輸出重定向到管道輸入 startupInfo.hStdOutput = hWrite; //把創(chuàng)建進(jìn)程的標(biāo)準(zhǔn)輸出重定向到管道輸入 startupInfo.wShowWindow = SW_HIDE;startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;char szCmdLine[1024];sprintf(szCmdLine, "cmd.exe /C %s", EXECDOSCMD);if (CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, NULL, NULL, NULL, &startupInfo, &processInfo) == 0) {printf("ERROR!! CreateProcess()=[0]. GetLastError()=[%d].\n", GetLastError());CloseHandle(hWrite);CloseHandle(hRead);return FALSE;}else {WaitForSingleObject(processInfo.hProcess, INFINITE);if (GetExitCodeProcess(processInfo.hProcess, &dwRetVal) == 0) {printf("ERROR!! GetExitCodeProcess()=[0]. GetLastError()=[%d].\n", GetLastError());}else {printf("The command runs successfully with returns code: [%d].\n", dwRetVal);}}CloseHandle(processInfo.hThread);CloseHandle(processInfo.hProcess);CloseHandle(hWrite);char szOutputBuffer[4096]; DWORD dwBytesRead;while (true) {memset(szOutputBuffer, 0x00, sizeof(szOutputBuffer));if (ReadFile(hRead, szOutputBuffer, 4095, &dwBytesRead, NULL) == FALSE)break;printf("result = [%s]\n", szOutputBuffer);}CloseHandle(hRead);return TRUE; }?
轉(zhuǎn)載于:https://www.cnblogs.com/moiez/p/6000049.html
總結(jié)
以上是生活随笔為你收集整理的匿名管道实现获取控制台程序输出的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 安洁科技有没有核心技术 体现在产品制造上
- 下一篇: HDU 1176 免费馅饼 矩阵取数