Managing the spawned process
There are a few methods, such as destroy()
, destroyForcibly()
(added in Java 8), isAlive()
(added in Java 8), and supportsNormalTermination()
(added in Java 9), which can be used to control the process spawned. These methods are available on the Process
object as well as on the ProcessHandle
object. Here, controlling would be just to check whether the process is alive, and if it is, then destroy the process.
In this recipe, we will spawn a long-running process and do the following:
- Check for its liveliness
- Check whether it can be stopped normally; that is, depending on the platform, the process has to be stopped by just using destroy or by using force destroy
- Stop the process
How to do it...
- Spawn a new process from the Java code, which runs the
sleep
command for, say, one minute, or 60 seconds:
ProcessBuilder pBuilder = new ProcessBuilder("sleep", "60"); Process p = pBuilder.inheritIO().start();
- Wait for, say, 10 seconds:
p.waitFor(10, TimeUnit.SECONDS...