"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve the Process ID (PID) of a Recently Launched Process in Java?

How to Retrieve the Process ID (PID) of a Recently Launched Process in Java?

Posted on 2025-03-24
Browse:721

How to Retrieve the Process ID (PID) of a Recently Launched Process in Java?

Retrieving Process ID of Recently Launched Process in Java Program

When starting a process within a Java program, it is often necessary to retrieve the process ID (PID) for further management or monitoring.

Question:

Consider the following code snippet that initiates a process:

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path");
try {
    Process p = pb.start();       
} 
catch (IOException ex) {}

How can we determine the PID of the newly created process using Java?

Answer:

Prior to Java 9, obtaining the PID of a child process involved platform-specific implementations. However, with the introduction of Process API enhancements in Java 9, a simplified approach is now available:

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path");
try {
    Process p = pb.start();
    long pid = p.pid();      
} catch (IOException ex) {
    // ...
}

By invoking the pid() method on the Process object, we can directly access the PID of the child process, regardless of the operating system.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3