Home > Java > javaTutorial > body text

How to Retrieve the PID of a Process Launched using ProcessBuilder in Java?

DDD
Release: 2024-10-25 08:14:29
Original
446 people have browsed it

How to Retrieve the PID of a Process Launched using ProcessBuilder in Java?

Retrieving the PID of a Process Launched from Java

When launching a process in Java using ProcessBuilder, you often need to obtain its process ID (PID) for further management or monitoring. Here's how you can achieve this:

In previous versions of Java, you could use Runtime.getRuntime().exec() to start a process and retrieve its PID using the ProcessHandle.pid() method. However, with the introduction of Java 9, ProcessBuilder offers a more refined approach.

<code class="java">import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;

public class GetProcessPID {

    public static void main(String[] args) {
        // Generate a random number for the process name
        String processName = "Process_" + ThreadLocalRandom.current().nextInt(1000);

        try {
            // Start the process with ProcessBuilder
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", processName);
            Process p = pb.start();

            // Retrieve and print the process PID
            long pid = p.pid();
            System.out.println("Process PID: " + pid);
        } catch (IOException e) {
            System.out.println("Error starting process: " + e.getMessage());
        }
    }
}</code>
Copy after login

This code demonstrates how to use ProcessBuilder to start a command prompt (cmd) window with a specified name (processName). The pid() method of the Process object is then used to obtain the PID of the newly created process, which is printed to the console.

Since Java 9, the pid() method is a straightforward way to retrieve the PID of processes launched using ProcessBuilder. It simplifies the process compared to using ProcessHandle in earlier Java versions.

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