1

I want to execute a program through the command line similar to java -jar xxx.jar
then get the process ID of the program
judge whether the process is alive or not by the process ID later.

//start a process
String command = "...";
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
//get the pid of process
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
                Class<?> clazz = Class.forName("java.lang.UNIXProcess");
                field = clazz.getDeclaredField("pid");
                ReflectionUtils.makeAccessible(field);
                pid = (Integer) field.get(process);
            }

Then, i want to determine if this process is alive,i tried like:

// judge the process is alive or not. By pid.
if (System.getProperty(Constants.SYSTEM_NAME).toLowerCase().contains("linux") || System.getProperty(Constants.SYSTEM_NAME).toLowerCase().contains("mac")) {
            process = RuntimeUtil.exec(BIN_BASH + " -c" + " ps -elf | grep " + pid);
        }

        if(process != null){
            String line;
            try(InputStream in = process.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(in,StandardCharsets.UTF_8))){
                while((line = br.readLine()) != null){
                    if(line.contains(pid)){
// i can't see the pid of my process (always)
                        return true;
                    }
                }
            } catch (IOException e) {
               //exception handle
            }
        }
GZK329
  • 11
  • 2
  • Try looking at [Verify if a process is running using its PID in JAVA](https://stackoverflow.com/q/21460775/16653700). – Alias Cartellano Sep 27 '22 at 16:49
  • 1
    Since Java 9, you can use `process.pid()` instead of using reflection. And if you know the pid, you can use what I added as comment to Bart-del's answer. Or, for the started process, `process.isAlive()`, available since Java 8. – Rob Spoor Sep 27 '22 at 17:33

1 Answers1

0

Since Java 9 there is standard library to get all alive process. With this you can simply find if process with pid is alive.

private boolean checkIsProcessAlive(Long pid)
{
    return ProcessHandle.allProcesses()
            .map(ProcessHandle::pid)
            .anyMatch(p -> p.equals(pid));
}

But there is one more way to reach this. When you create process object with Process process = pb.start(); you can check if process is alive with process.isAlive(); method.

Bart-del
  • 36
  • 5
  • If you know the pid, just use `ProcessHandle.of`: `ProcessHandle.of(pid).map(ProcessHandle::isAlive).orElse(false)` – Rob Spoor Sep 27 '22 at 17:30