Home > Java > javaTutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-26 06:05:03
Original
504 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!