devxlogo

Executing a Subprocess

Executing a Subprocess

To be able to read from two streams, you need two threads. A common mistake is to start a process and then only read standard out (stdout. Another mistake is to read one after the other. In both cases, the process may block if it writes more than the buffer size.

Here is a class that may be used to copy one stream to another:

 /** Echoes the output from one stream into another. */  class StreamTracker implements Runnable  {    private InputStream iIn;    private OutputStream iOut;    /** Setup the streams. */    StreamTracker(InputStream inIn, OutputStream inOut)    {      iIn = inIn;      iOut = inOut;    }    /** Start echoing, proceed until eof. */    public void run()    {      try {        int lInCh = 0;        while (lInCh != -1) {          lInCh = iIn.read();          iOut.write(lInCh);        }      } catch (IOException e) {        ; // thats it      }    }  }

This clears the way for you to start a process like this:

rtime = Runtime.getRuntime();Process child = rtime.exec("/bin/bash");

The process is running and the following will track it, using our StreamTracker:

 try {  StreamTracker s1 =     new StreamTracker(child.getInputStream(), System.out);  new Thread(s1).start();  StreamTracker s2 =    new StreamTracker(child.getErrorStream(), System.out);  new Thread(s2).start();  child.waitFor(); } catch (InterruptedException e) {      ; }

In this case, the result is printed on System.out.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist