Chapter 18. Managing Processes in Java
With a very quick tour through some of the big new features of Java 9, as well as those from a couple of previous releases, let's turn our attention to applying some of these new APIs in a practical manner. We'll start with a simple process manager.
While having your application or utility handle all of your user's concerns internally is usually ideal, occasionally you need to run (or shell out to) an external program for a variety of reasons. From the very first days of Java, this was supported by the JDK via the Runtime
class via a variety of APIs. Here is the simplest example:
Process p = Runtime.getRuntime().exec("/path/to/program");
Once the process has been created, you can track its execution via the Process
class, which has methods such as getInputStream()
, getOutputStream()
, and getErrorStream()
. We have also had rudimentary control over the process via destroy()
and waitFor()
. Java 8 moved things forward by adding destroyForcibly()
and waitFor...