System.Diagnostics.Process: avoid deadlocks in RedirectStandardInput/Output (Lucian Wischik)

VBTeam

It’s common that you want to launch an external process but supply input and capture the output. Here’s one attempt: 

‘ BAD CODE

Using p As New System.Diagnostics.Process

    p.StartInfo.FileName = “cat”

    p.StartInfo.UseShellExecute = False

    p.StartInfo.RedirectStandardOutput = True

    p.StartInfo.RedirectStandardInput = True

    p.Start()

    p.StandardInput.Write(“world” & vbCrLf & “hello”)

    p.StandardInput.Close()

    Dim op = p.StandardOutput.ReadToEnd()

    p.WaitForExit()

    p.Close()

    Console.WriteLine(“OUTPUT:”) : Console.WriteLine(op)

End Using

This code has a deadlock bug in it. That’s because of the possibility that “p” needs to write to StandardOutput before it’s yet finished reading all of StandardInput: there won’t be anyone to read from StandardOutput, and it might fill up!

The MSDN documentation says that the answer is to use multiple threads. So here’s code that uses multiple threads to avoid the deadlock: http://blogs.msdn.com/lucian/archive/2008/12/29/system-diagnostics-process-redirect-standardinput-standardoutput-standarderror.aspx

 

 

0 comments

Leave a comment

Feedback usabilla icon