温馨提示×

CreateProcess和CreatePipe在VC ++中执行进程并以字符串形式返回输出

c++
小云
151
2023-09-27 10:00:53
栏目: 编程语言

以下是在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变量以执行其他命令。

0