我有一个程序,其中父进程生成子进程,然后与之进行通信。
父进程是一个VB应用程序,子进程是一个C#控制台应用程序。
父进程(暂时删除了错误处理):
Private Function InitialieExtConversionProcess() As Boolean
Dim lResult As Long
Dim SA As SECURITY_ATTRIBUTES
Dim sInfo As STARTUPINFO
Dim sCommandLine As String
SA.bInheritHandle = True
'Create the pipe that Hyperspace will write to
lResult = CreatePipe(m_pipeOut.hReadPipe, m_pipeOut.hWritePipe, SA, 0)
'Ensure that the read handle is not inherited
lResult = SetHandleInformation(m_pipeOut.hReadPipe, HANDLE_FLAG_INHERIT, 0)
'Create the pipe that Hyperspace will read from
lResult = CreatePipe(m_pipeIn.hReadPipe, m_pipeIn.hWritePipe, SA, 0)
'Ensure that the write handle is not inherited
lResult = SetHandleInformation(m_pipeIn.hWritePipe, HANDLE_FLAG_INHERIT, 0)
'Create the external process
sCommandLine = "some_path\ExtProcess.exe"
sInfo.hStdInput = m_pipeIn.hReadPipe
sInfo.hStdError = m_pipeOut.hWritePipe
sInfo.hStdOutput = m_pipeOut.hWritePipe
sInfo.dwFlags = STARTF_USESTDHANDLES
lResult = CreateProcess(0, sCommandLine, 0, 0, 1, CREATE_NO_WINDOW, 0, 0, sInfo, m_pInfo)
InitialieExtConversionProcess = True
End Function
然后我使用WriteFile和ReadFile来编写和读取子进程
lResult = WriteFile(m_pipeIn.hWritePipe, sOutput, Len(sOutput), 0, 0)
...
lResult = ReadFile(m_pipeOut.hReadPipe, sInput, Len(sInput), 0, ByVal 0)
子进程(C#控制台应用程序):
IntPtr hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
IntPtr hInput = GetStdHandle(STD_INPUT_HANDLE);
AnonymousPipeClientStream pipeClientRead = new AnonymousPipeClientStream(PipeDirection.In, hInput.ToString());
AnonymousPipeClientStream pipeClientWrite = new AnonymousPipeClientStream(PipeDirection.Out, hOutput.ToString());
arr = new byte[300];
pipeClientRead.Read(arr, 0, 300);
...
arr = Encoding.ASCII.GetBytes(strResult);
pipeClientWrite.Write(arr, 0, arr.Length);
pipeClientWrite.Flush();
这里的沟通正如预期的那样。我能够成功读写。
当父进程关闭时,子进程中的Read操作返回false。但是当子进程自行杀死时(如下所示),父进程继续等待ReadFile。为什么会这样?
arr = new byte[300];
pipeClientRead.Read(arr, 0, 300);
--->Environment.exit(1);<----
arr = Encoding.ASCII.GetBytes(strResult);
pipeClientWrite.Write(arr, 0, arr.Length);
pipeClientWrite.Flush();
我密切关注这个msdn示例: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
答案 0 :(得分:0)
我发现了什么是错误的。
我需要在创建后关闭子进程的句柄。
lResult = CreateProcess(0, sCommandLine, 0, 0, 1, CREATE_NO_WINDOW, 0, 0, sInfo, m_pInfo)
CloseHnadle(m_pipeIn.hReadPipe)
CloseHandle(m_pipeOut.hWritePipe)