Retrieving the PID of a Recently Started Process in Java
When starting a process using the ProcessBuilder class in Java, there may be a need to obtain its process ID (PID) for further operations. This article addresses this requirement by showcasing a straightforward method available in Java 9 and above.
To launch a process, you can utilize the following code:
<code class="java">ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path"); try { Process p = pb.start(); } catch (IOException ex) {}</code>
To determine the PID of the process that was just started, Java 9 introduced a convenient API in the Process class. The pid() method effectively retrieves the PID of the process, making this task effortless:
<code class="java">ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path"); try { Process p = pb.start(); long pid = p.pid(); } catch (IOException ex) { // Error handling }</code>
By leveraging this enhanced functionality, you can seamlessly obtain the PID of the process you've recently initiated within your Java program.
The above is the detailed content of How to Get the PID of a Recently Started Process in Java?. For more information, please follow other related articles on the PHP Chinese website!