Home  >  Article  >  Java  >  How can I retrieve the Process ID of a recently started process in Java?

How can I retrieve the Process ID of a recently started process in Java?

DDD
DDDOriginal
2024-10-25 13:04:30653browse

How can I retrieve the Process ID of a recently started process in Java?

Retrieving Process ID of Recently Started Process in Java

To initiate a new process, the ProcessBuilder class and its start() method can be employed. However, subsequently determining the PID (process identifier) of the process remains a distinct challenge.

In Java 9 and later versions, a straightforward solution is provided through the pid() method of the Process class. This method returns the PID of the process as a long value. The implementation below demonstrates this approach:

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

In this example, after starting the process with pb.start(), the pid() method retrieves and assigns the PID to the pid variable. Alternatively, if the Java version is prior to Java 9, external tools or libraries may be necessary to obtain the PID.

The above is the detailed content of How can I retrieve the Process ID 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