문제

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

다른 팁

you can try execute command

pidof <program name>

for you to find the pid of your program.

It is in Linux env.

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

System.out.println("Your pid is " + Process.getCurrentPid());
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top