Obtaining the process information of the spawned process
In our previous recipe, we saw how to get the process information for the current Java process. In this recipe, we will look at how to get the process information for a process spawned by the Java code; that is, by the current Java process. The APIs used will be the same as we saw in the previous recipe, except for the way the instance of ProcessHandle
is implemented.
Getting ready
In this recipe, we will make use of a Unix command, sleep
, which is used to pause the execution for a period of time in seconds.
How to do it...
Follow these steps:
- Spawn a new process from the Java code, which runs the
sleep
command:
ProcessBuilder pBuilder = new ProcessBuilder("sleep", "20"); Process p = pBuilder.inheritIO().start();
- Get the
ProcessHandle
instance for this spawned process:
ProcessHandle handle = p.toHandle();
- Wait for the spawned process to complete execution:
int exitValue = p.waitFor();
- Use
ProcessHandle
to get...