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

Published 30 December 08 09:00 AM

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

 

 

by VBTeam
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# System.Diagnostics.Process: avoid deadlocks in RedirectStandardInput/Output (Lucian Wischik) | Coded Style said on December 30, 2008 12:19 PM:

PingBack from http://www.codedstyle.com/systemdiagnosticsprocess-avoid-deadlocks-in-redirectstandardinputoutput-lucian-wischik/

# Ted said on January 7, 2009 5:17 PM:

The code has another bug.  The sub-process executed could hang or go into an infinite loop and never terminate.  

This is the basic case of not blocking on a subprocess by creating a thread to load and execute it.  It has nothing really to do with standard input and standard output.

P.s. Thanks for referring to the old unix cat utility.  I've used many of them, sed and tiffcp especially, for processing data from within a .net application.

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker