Retrieving the PID of a Process Started from Java
When launching a process from within a Java program, it may be necessary to obtain the process's identification number (PID). This information is crucial for tasks such as process management, synchronization, and control.
To start a process, the ProcessBuilder class is typically utilized. The following code snippet demonstrates how to launch a process:
<code class="java">ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path"); try { Process p = pb.start(); } catch (IOException ex) {}</code>
Retrieving the PID
In Java 8 and earlier versions, obtaining the PID of the started process was not straightforward. However, with the introduction of Java 9, the Process class gained a new method called pid(). This method directly returns the process's ID.
To use this method, simply add the following line of code:
<code class="java">long pid = p.pid(); // where 'p' is the Process object</code>
This line assigns the PID of the started process to the variable pid.
The above is the detailed content of How to Get the PID of a Process Launched from Java?. For more information, please follow other related articles on the PHP Chinese website!