我尝试在Windows中使用CreateProcess()重定向cmd.exe的stdout和stdin。只要我运行简单的命令或打开GUI应用程序,它就可以正常工作,但是如果我尝试运行像Python这样的软件,它就不再输出(也无法通过stdin获取输入)。
代码示例:
#include <windows.h>
#include <iostream>
#include <string>
#include <thread>
using namespace std;
HANDLE child_input_read;
HANDLE child_input_write;
HANDLE child_output_read;
HANDLE child_output_write;
void writeToPipe()
{
while (true)
{
DWORD bytes_written;
string msg;
getline(cin, msg);
msg += '\n';
BOOL success = WriteFile(child_input_write, msg.c_str(), msg.size(), &bytes_written, NULL);
if (!success)
{
break;
}
}
}
void readFromPipe()
{
while (true)
{
DWORD bytes_read;
char buffer[512];
BOOL success = ReadFile(child_output_read, buffer, sizeof(buffer)-1, &bytes_read, NULL);
buffer[bytes_read] = 0;
if (!success)
{
break;
}
cout << buffer;
}
}
void createCmdProcess()
{
PROCESS_INFORMATION process_info;
STARTUPINFO startup_info;
SECURITY_ATTRIBUTES security_attributes;
// Set the security attributes for the pipe handles created
security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
security_attributes.bInheritHandle = TRUE;
security_attributes.lpSecurityDescriptor = NULL;
CreatePipe(&child_output_read, &child_output_write, &security_attributes, 0);
CreatePipe(&child_input_read, &child_input_write, &security_attributes, 0);
// Create the child process
ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION));
ZeroMemory(&startup_info, sizeof(STARTUPINFO));
startup_info.cb = sizeof(STARTUPINFO);
startup_info.hStdInput = child_input_read;
startup_info.hStdOutput = child_output_write;
startup_info.hStdError = child_output_write;
startup_info.dwFlags |= STARTF_USESTDHANDLES;
CreateProcess(NULL, "cmd.exe", NULL, NULL, TRUE, 0, NULL, NULL, &startup_info, &process_info);
}
int main()
{
createCmdProcess();
thread t(writeToPipe);
thread t2(readFromPipe);
t.join();
t2.join();
system("pause");
}
cmd.exe
可以工作,Python命令也可以,但是Python的交互模式不行。 - Harry Johnston