我正在遵循此example,但代码太多了,我真的不确定他们在哪里使用了一些简化。 因此,我尝试创建一个简短得多的示例,但无法使管道正常工作。
#include <cstdlib>
#include <cstdio>
#include <windows.h>
int main() {
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
SECURITY_ATTRIBUTES saAttr = {};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
char* command = "example.exe";
if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)) printf("Stdin CreatePipe");
if (! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) ) printf("StdoutRd CreatePipe");
STARTUPINFO siStartInfo = {};
PROCESS_INFORMATION piProcInfo = {};
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.hStdInput = g_hChildStd_IN_Rd;
siStartInfo.dwFlags = STARTF_USESTDHANDLES;
CreateProcess(NULL,
command, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_NEW_CONSOLE, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
Sleep(1000);
printf("writing to process\n");
DWORD dwWritten;
WriteFile(siStartInfo.hStdInput, "hello world", 11, &dwWritten, NULL);
printf("reading from process\n");
DWORD dwRead;
const int BUFSIZE = 1024;
CHAR chBuf[BUFSIZE];
ReadFile(siStartInfo.hStdOutput, chBuf, BUFSIZE, &dwRead, NULL);
if ( dwRead > 0 ) {
printf("Read from the pipe: %s\n", chBuf);
} else {
printf("Nothing to read from stdout.\n");
}
return 0;
}
example.exe似乎永远都不会接收任何数据,无论我将哪个管道手柄放入WriteFile-Line中。
example.exe只是一个伪程序,如下所示:
#include <cstdlib>
#include <cstdio>
int main() {
printf("This is an external process.\n");
char Buffer[1024];
fgets(Buffer, 1024 , stdin);
printf("GOT: %s\n", Buffer);
return 0;
}
我想知道的是如何设置管道,以便在使用管道启动过程时可以对其进行读写操作。