Hi and welcome to DeveloperLife, written by Nadav Azaria and Roi Gamliel. In this blog we write about our own experience in software development, trying to share our knowledge following new technologies we adopt or problems we face.

Tuesday, January 1, 2013

Executing a Command Line Executable From Java

In this post we'll deal with a common need for Java developers. Execute and manage an external process from within Java. Since this task is quite common we set out to find a Java library to help us accomplish it.
The requirements from such a library are:

Execute the process asynchronously.

Ability to abort the process execution.

Ability to wait for process completion.

On process output notifications.

Ability to kill the process in case it hung.

Get the process exit code.

The native JDK does not help much. Fortunately, we have Apache Commons Exe. Indeed it is much easier but still not as straightforward as we hoped. We wrote a small wrapper on top of it.
Here is the method signature we expose:

Instance of ProcessExecutorHandler is passed to the function. This instance is actually a listener for any process output. This covers section 4 in our requirement.

Last but not least you supply a timeout. If the process execution takes more than said timeout you assume the process hung and you will end it. In that case the error code returned by the process will be -999.