如何获取生成的java进程的PID [英] How do I obtain the PID of a spawned java process

查看:576
本文介绍了如何获取生成的java进程的PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写几个java程序,并且在完成我想做的任何事情后,需要在单独的JVM中终止/清理。为此,我需要获取我正在创建的java进程的PID。

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.

推荐答案

jps -l <​​/ code>适用于Windows和Unix。您可以使用 Runtime.getRuntime()。exec 从java程序中调用此命令。 jps -l <​​/ code>的示例输出如下:

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

你可能需要解析这个和然后检查完​​全限定的名称,然后从相应的行获取pid。

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]);
        }
    }
}

这篇关于如何获取生成的java进程的PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆