如何通过 JAVA 在 linux 中获取 java.lang.Process 的 PID

How to get PID of java.lang.Process in linux by JAVA

我想出了两种方法来解决这个问题,但都达不到预期。

  1. 我使用 'Process' 执行“ps -ef”

    我可以通过这个方法获取所有行,我可以通过我的 运行 过滤它们 command.But 如果我有很多相同的命令 process.This 是行不通的。

  2. 我用JNA获取PID



    Field field = null;
    Integer pid = -1;
    try {
        Class clazz = Class.forName("java.lang.UNIXProcess");
        field = clazz.getDeclaredField("pid");
        field.setAccessible(true);
        pid = (Integer) field.get(process);
    } catch (Throwable e) {
        e.printStackTrace();
    }

这种方式只能得到运行window的PID。这不是进程的真实 PID。

我该怎么办?

谢谢!

Java 9

Java 9 引入了一些 "nice" 变化,一个是包含了一个 Process 的原生 PID - 请参阅 Process#pid 了解更多详情

import java.io.IOException;
import java.io.InputStream;

public class Test {

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder("/Applications/Xcode.app/Contents/MacOS/Xcode");
        pb.redirectErrorStream(true);
        Process p = pb.start();
        // Yes, I'm a bad developer, but I just want to demonstrate
        // the use of the PID method :/
        new Thread(new Consumer(p.getInputStream())).start();
        System.out.println("PID = " + p.pid());
        p.waitFor();
        System.out.println("Exit with " + p.exitValue());
    }

    public static class Consumer implements Runnable {
        private InputStream is;

        public Consumer(InputStream is) {
            this.is = is;
        }

        @Override
        public void run() {
            try {
                int value = -1;
                while ((value = is.read()) != -1) {
                    // I'm ignoring it for brevity
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}

您还可以获得对 ProcessHandle for the Process via the Process#toHandle 方法的引用,这很好