匿名管道实现获取控制台程序输出
生活随笔
收集整理的這篇文章主要介紹了
匿名管道实现获取控制台程序输出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本代碼經過嚴格單元測試,如果誰能其中檢測到代碼bug,我請他一杯最好喝的咖啡!??
?
#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; //把創建進程的標準錯誤輸出重定向到管道輸入 startupInfo.hStdOutput = hWrite; //把創建進程的標準輸出重定向到管道輸入 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; }?
轉載于:https://www.cnblogs.com/moiez/p/6000049.html
總結
以上是生活随笔為你收集整理的匿名管道实现获取控制台程序输出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安洁科技有没有核心技术 体现在产品制造上
- 下一篇: 常见设备分辨率大小,响应式必备啊