Java 9 : How to get Process Information from Process Id in Java

Points to Remember

  1. You need to run this code with Java 1.9
  2. ProcessHandle.of(Long processId) method will return an object of Optional<ProcessHandle>.
  3. Optional is a class introduced in java 8 which is a container object which may or may not contain a non-null value. It has methods boolean isPresent() which returns true if a value is present else returns false. T get() method returns the object if present or else throws NoSuchElementException.

Read More

Get Process Information from Process Id

If we have the process id of a process, then we can get the information about the process as shown in the following code.

import java.io.IOException;
import java.lang.ProcessHandle;
import java.lang.Process;

/**
 * @author ekiras
 */
public class DestroyProcess {

    public static void main(String[] args) throws InterruptedException {
        try {
            ProcessHandle processHandle = startProcess("tail -F /dev/null").toHandle();
            printProcessInfo(processHandle);
            destroyProcess(processHandle);
            Thread.sleep(1000);
            printProcessInfo(processHandle);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void printProcessInfo(ProcessHandle processHandle){
        System.out.println("---Process Info---");
        System.out.println(" Process Id :: " + processHandle.getPid());
        System.out.println(" Process isAlive() :: " + processHandle.isAlive());
        System.out.println(" Process children :: " + processHandle.children().count());
        System.out.println(" Process supportsNormalTermination() :: " + processHandle.supportsNormalTermination());
        System.out.println(" Process Info :: " + processHandle.info().toString());

    }

    public static void destroyProcess(ProcessHandle process) throws IllegalStateException{
        System.out.println("Going to destroy Process with id :: " + process.getPid());
        process.destroy();
    }

    public static Process startProcess(String command) throws IOException {
        System.out.println("Start Process :");
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        return process;
    }

}

We have a process running with the process id 678. Read How to start a new Process. When we run the above code with a valid process id it will result in the following output.

> java GetProcessById 678
---Process Info---
 Process Id :: 678
 Process isAlive() :: true
 Process children :: 0
 Process supportsNormalTermination() :: true
 Process Info :: [user: Optional[root], cmd: /usr/bin/tail, args: [-f, /dev/null], startTime: Optional[2016-11-14T08:36:02.310Z], totalTime: Optional[PT0S]]

When we run the above code with an invalid process id, we will get the following output.

>  java GetProcessById 6785
 No process found by Process Id :: 6785

No comments:

Powered by Blogger.