Home > Java > javaTutorial > body text

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

Patricia Arquette
Release: 2024-10-25 10:50:02
Original
155 people have browsed it

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

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

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!

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!