我正在使用msdn创建子进程的文章,因为它非常接近我想要实现的目标。
创建子进程c#的问题,使用管道重定向有帮助找到…
您的代码中存在一些错误。
第一,
childOutRead = GetStdHandle(STD_OUTPUT_HANDLE); parentInRead = GetStdHandle(STD_INPUT_HANDLE); 从CreatePipe获取2个句柄,已经重置为stdhandle,并丢失了管道句柄。
childOutRead = GetStdHandle(STD_OUTPUT_HANDLE); parentInRead = GetStdHandle(STD_INPUT_HANDLE);
第二,
CreatePipe(&childOutWrite, &childOutRead, &secAttr, 0);
应该 CreatePipe(&childOutRead, &childOutWrite, &secAttr, 0)
CreatePipe(&childOutRead, &childOutWrite, &secAttr, 0)
第三,
SetHandleInformation()中的句柄不正确。
好吧,让我们回答你的问题。
对于隐藏子进程,其stdin / stdout句柄被设置为管道句柄,因此您无法看到控制台,但它确实在后台运行。 我对您的示例做了一些更改(为简单起见,不使用异步):
Parent.cpp
#include <windows.h> #include <iostream> #include <stdio.h> HANDLE childInRead = NULL; HANDLE W1 = NULL; HANDLE W2 = NULL; HANDLE R2 = NULL; HANDLE R1 = NULL; #define BUFSIZE 4096 void CreateChildProcess() { TCHAR applicationName[] = TEXT("ChildTalk.exe"); PROCESS_INFORMATION pi; STARTUPINFO si; BOOL success = FALSE; ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.hStdError = W1; si.hStdOutput = W1; si.hStdInput = R2; si.dwFlags |= STARTF_USESTDHANDLES; success = CreateProcess(NULL, applicationName, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi); if (!success) { printf("Error creating child process \n"); } else { printf("Child process successfuly created \n"); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } } int main() { printf("Parent process running.... \n"); DWORD dRead, dWritten; CHAR chBuf[BUFSIZE] = "hello"; BOOL bSuccess = FALSE; SECURITY_ATTRIBUTES secAttr; secAttr.nLength = sizeof(SECURITY_ATTRIBUTES); secAttr.bInheritHandle = TRUE; secAttr.lpSecurityDescriptor = NULL; printf("Creating first pipe \n"); if (!CreatePipe(&R1, &W1, &secAttr, 0)) { printf("\n error creating first pipe \n"); } printf("Creating second pipe \n"); if (!CreatePipe(&R2, &W2, &secAttr, 0)) { printf("\n error creating second pipe \n"); } if (!SetHandleInformation(R1, HANDLE_FLAG_INHERIT, 0)) { printf("\n R1 SetHandleInformation \n"); } if (!SetHandleInformation(W2, HANDLE_FLAG_INHERIT, 0)) { printf("\n W1 SetHandleInformation \n"); } printf("\n Creating child process..... \n"); HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE); CreateChildProcess(); for (;;) { printf("Inside for loop \n"); //1. read from stdin bSuccess = ReadFile(hStdIn, chBuf, BUFSIZE, &dRead, NULL); if (!bSuccess) { printf("error reading \n"); break; } //2. write to Pipe2 bSuccess = WriteFile(W2, chBuf, 100, &dWritten, NULL); if (!bSuccess) { printf("error reading \n"); break; } //3. read from Pipe1 bSuccess = ReadFile(R1, chBuf, BUFSIZE, &dRead, NULL); if (!bSuccess) { printf("error reading \n"); break; } //4. write to stdout bSuccess = WriteFile(hStdOut, chBuf, 100, &dWritten, NULL); if (!bSuccess) { printf("error reading \n"); break; } } return 0; }
它的逻辑过程: