Thursday, February 09, 2006

Starting a separate process from inside a Java Application

The short answer is to use Runtime.getRuntime().exec(). But there is a catch. You have to handle the input and output from this newly created process to avoid process hangings.

A good article can be found at http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html.

The best practice here is to have something like the StreamGobbler which creates a separate thread and it will consume the stdout and stderr. You use Runtime.getRuntime().exec() to start the process, use the Process object it returns and get the ErrorStream and InputStream and pass it to the StreamGobber. Remember not to omit the error stream, because if your newly created process generate errors, and not being consumed in time, it will also hang.

I can successfully start processes which generate lots of output from this standalone application. But I have failed to do that from inside a J2ee container. I haven't figured out what's causing the problems yet. It seems that the process will be generated for a short period of time then got killed. Something that I can keep in mind for further investigation in the future.

0 Comments:

Post a Comment

<< Home