Home  >  Article  >  Java  >  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?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 10:50:02259browse

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:

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

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:

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

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

The above is the detailed content of How to Retrieve the Process ID (PID) of a Recently Launched Process in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn