Java 9 : How to start a new Process and get process id

Points to Remember

  1. This post used Java 1.9 since ProcessHandle was introduced in Java 1.9.

Read More

Get the Current Process Information.

In this example we will try to get information about the current process. For this we will use the m

import java.io.IOException;

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

    public static void main(String[] args) {
        try {
            Process process = startProcess("tail -F /dev/null");
            printProcessInfo(process.toHandle());
        } 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 Process startProcess(String command) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        return process;
    }

}

When we run the above code, it will return the following output.

---Process Info---
 Process Id :: 1865
 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-16T12:40:10.460Z], totalTime: Optional[PT0S]]

No comments :

Post a Comment