How do I obtain the PID of a spawned java process

只愿长相守 提交于 2019-12-02 07:13:35

问题


I am writing several java programs and will need to kill off/clean up in a seperate JVM after I am done with whatever I wanted to do. For this, I will need to get the PID of the java process which I am creating.


回答1:


jps -l works both on Windows and Unix. You can invoke this command from your java program using Runtime.getRuntime().exec. Sample output of jps -l is as follows

9412 foo.bar.ClassName
9300 sun.tools.jps.Jps

You might need to parse this and then check for the fully qualified name and then get the pid from the corresponding line.

private static void executeJps() throws IOException {
    Process p = Runtime.getRuntime().exec("jps -l");
    String line = null;
    BufferedReader in = new BufferedReader(new InputStreamReader(
                                                p.getInputStream(), "UTF-8"));

    while ((line = in.readLine()) != null) {
        String [] javaProcess = line.split(" ");
        if (javaProcess.length > 1 && javaProcess[1].endsWith("ClassName")) {
            System.out.println("pid => " + javaProcess[0]);
            System.out.println("Fully Qualified Class Name => " + 
                                           javaProcess[1]);
        }
    }
}



回答2:


you can try execute command

pidof <program name>

for you to find the pid of your program.

It is in Linux env.




回答3:


Note that Java 9 is going to expose some system-agnostic methods such as:

System.out.println("Your pid is " + Process.getCurrentPid());


来源:https://stackoverflow.com/questions/7834270/how-do-i-obtain-the-pid-of-a-spawned-java-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!