Home  >  Article  >  Java  >  How to Get the PID of a Recently Started Process in Java?

How to Get the PID of a Recently Started Process in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 06:05:03485browse

How to Get the PID of a Recently Started Process in Java?

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!

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