Harald Kirsch

genug Unfug.

Jniexec — real Java exec

Java Native Interface exec (fork) implementation

Java's Runtime.exec() is a sad state of affairs as compared to the management facilities for sub processes provided by any POSIX shell or the underlying C library and system calls on a UNIX/Linux system. There are several related feature requests in SUN's Java bug database. Since it is hard to devise a solution that is portable to all systems, we may have to wait for an official fix another few decades.

Since my work and interest mainly includes Linux (Unix) machines, I decided to shorten the time of wait and provide a result that works at least on these architectures. Jniexec provides a Java Native Interface wrapper around the fork(2) and execlp(3) pair of functions. It comes accompanied with two easy to use Java wrapper classes. In particular the following features are provided.


  • True sub process fork/exec of a command defined by a String[]. There is no need for an intervening shell command.
  • Native I/O redirection. The I/O file descriptors of the subprocess can be redirected to anything with a FileDescriptor. The Java parent process does not need to shuffle the data itself.
  • Redirection of every file descriptor, not just standard input, output and error.
  • Native pipelines. Several sub processes can be run in a pipeline connecting standard output of one sub process to the standard input of the next by I/O redirection. The Java parent process does not need to shuffle the data between the sub processes.
  • Still, the Java parent process can arrange to write to the pipeline's standard input, read its standard output, any of the standard error streams or any other pipe connected to the sub processes.
  • Blocking or non-blocking waits on all or individual processes of the pipeline.
  • Retrieval of exit codes of all sub processes of the pipeline as well as a summary ok/failure status.