2016-12-27 16 views
0

我有一个程序,其中父进程产生一个子进程,然后与其通信。匿名管道:父进程中的ReadFile继续等待子进程被终止时

父进程是一个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(); 

沟通在这里按预期工作。我能够成功读写。

当父进程关闭时,子进程中的读操作返回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

我发现了什么misisng。

我需要在创建后关闭子进程的句柄。

lResult = CreateProcess(0, sCommandLine, 0, 0, 1, CREATE_NO_WINDOW, 0, 0, sInfo, m_pInfo) 
CloseHnadle(m_pipeIn.hReadPipe) 
CloseHandle(m_pipeOut.hWritePipe) 
相关问题