Я следую этому примеру , но это немного много кода, и я действительно не уверен, где они использовали некоторые упрощения.Поэтому я попытался создать намного более короткий пример, но я не могу заставить каналы работать должным образом.
#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;
}
Я хотел бы знать, как я должен настроить каналы,так что я могу читать / писать им, если я использую их для запуска процесса.