以下是在VC ++中使用CreateProcess和CreatePipe執行進程并以字符串形式返回輸出的示例代碼:
#include <windows.h>
#include <iostream>
#include <string>
std::string ExecuteCommand(const std::string& cmd)
{
SECURITY_ATTRIBUTES securityAttributes;
securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
securityAttributes.bInheritHandle = TRUE;
securityAttributes.lpSecurityDescriptor = NULL;
HANDLE StdOutRead, StdOutWrite;
CreatePipe(&StdOutRead, &StdOutWrite, &securityAttributes, 0);
SetHandleInformation(StdOutRead, HANDLE_FLAG_INHERIT, 0);
STARTUPINFOA startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.hStdOutput = StdOutWrite;
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
PROCESS_INFORMATION processInfo;
ZeroMemory(&processInfo, sizeof(processInfo));
if (!CreateProcessA(NULL, const_cast<LPSTR>(cmd.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInfo))
{
std::cerr << "Failed to execute command: " << cmd << std::endl;
return "";
}
CloseHandle(StdOutWrite);
DWORD bytesRead;
const int bufferSize = 4096;
char buffer[bufferSize];
std::string output;
while (ReadFile(StdOutRead, buffer, bufferSize - 1, &bytesRead, NULL))
{
if (bytesRead == 0)
break;
buffer[bytesRead] = '\0';
output += buffer;
}
CloseHandle(StdOutRead);
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
return output;
}
int main()
{
std::string cmd = "dir";
std::string output = ExecuteCommand(cmd);
std::cout << "Command output: " << std::endl;
std::cout << output << std::endl;
return 0;
}
上述代碼使用CreatePipe創建了一個匿名管道,將進程的輸出重定向到管道的寫入端,然后使用ReadFile從管道的讀取端讀取輸出。最后,使用CreateProcess啟動進程并等待其完成。
在上述示例中,cmd變量包含要執行的命令,該命令是一個簡單的"dir"命令,它會列出當前目錄中的文件和文件夾。您可以根據需要更改cmd變量以執行其他命令。