出處:https://blog.csdn.net/weixin_43903378/article/details/105297406
頭文件
#ifndef _PIPE_CMD_H_ #define _PIPE_CMD_H_ #include <Windows.h> // 執行 cmd 命令, 並獲取執行結果數據 BOOL PipeCmd(char *pszCmd, char *pszResultBuffer, DWORD dwResultBufferSize); #endif
源文件
#include "stdafx.h" #include "PipeCmd.h" void ShowError(char *pszText) { char szErr[MAX_PATH] = {0}; ::wsprintf(szErr, "%s Error[%d]\n", pszText, ::GetLastError()); ::MessageBox(NULL, szErr, "ERROR", MB_OK); } // 執行 cmd 命令, 並獲取執行結果數據 BOOL PipeCmd(char *pszCmd, char *pszResultBuffer, DWORD dwResultBufferSize) { HANDLE hReadPipe = NULL; HANDLE hWritePipe = NULL; SECURITY_ATTRIBUTES securityAttributes = {0}; BOOL bRet = FALSE; STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; // 設定管道的安全屬性 securityAttributes.bInheritHandle = TRUE; securityAttributes.nLength = sizeof(securityAttributes); securityAttributes.lpSecurityDescriptor = NULL; // 創建匿名管道 bRet = ::CreatePipe(&hReadPipe, &hWritePipe, &securityAttributes, 0); if (FALSE == bRet) { ShowError("CreatePipe"); return FALSE; } // 設置新進程參數 si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.wShowWindow = SW_HIDE; si.hStdError = hWritePipe; si.hStdOutput = hWritePipe; // 創建新進程執行命令, 將執行結果寫入匿名管道中 bRet = ::CreateProcess(NULL, pszCmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi); if (FALSE == bRet) { ShowError("CreateProcess"); } // 等待命令執行結束 ::WaitForSingleObject(pi.hThread, INFINITE); ::WaitForSingleObject(pi.hProcess, INFINITE); // 從匿名管道中讀取結果到輸出緩沖區 ::RtlZeroMemory(pszResultBuffer, dwResultBufferSize); ::ReadFile(hReadPipe, pszResultBuffer, dwResultBufferSize, NULL, NULL); // 關閉句柄, 釋放內存 ::CloseHandle(pi.hThread); ::CloseHandle(pi.hProcess); ::CloseHandle(hWritePipe); ::CloseHandle(hReadPipe); return TRUE; }