Home > Java > javaTutorial > body text

How to Get the PID of a Process Launched from Java?

DDD
Release: 2024-10-25 10:13:31
Original
409 people have browsed it

How to Get the PID of a Process Launched from Java?

Retrieving the PID of a Process Started from Java

When launching a process from within a Java program, it may be necessary to obtain the process's identification number (PID). This information is crucial for tasks such as process management, synchronization, and control.

To start a process, the ProcessBuilder class is typically utilized. The following code snippet demonstrates how to launch a process:

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

Retrieving the PID

In Java 8 and earlier versions, obtaining the PID of the started process was not straightforward. However, with the introduction of Java 9, the Process class gained a new method called pid(). This method directly returns the process's ID.

To use this method, simply add the following line of code:

<code class="java">long pid = p.pid();  // where 'p' is the Process object</code>
Copy after login

This line assigns the PID of the started process to the variable pid.

The above is the detailed content of How to Get the PID of a Process Launched from 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
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!