Get subprocess id in Java

前端 未结 5 886
悲&欢浪女
悲&欢浪女 2020-12-06 05:55

I\'m creating subprocesses in this way:

String command = new String(\"some_program\");

Process p = Runtime.getRuntime().exec(command);

How

相关标签:
5条回答
  • 2020-12-06 06:07

    Trivial on linux:

    String pid = new File("/proc/self").getCanonicalFile().getName();
    
    0 讨论(0)
  • 2020-12-06 06:10

    Well there is no documented way to do this, but it happens that the Process implementation class is UNIXProcess, and it has a pid field. So you could use reflection to access this private field to get the ID. Googling around you will find other tricks of calling another shell to get ps output and that kind of thing. Nothing easy.

    0 讨论(0)
  • 2020-12-06 06:18

    From here

    public static void main(String[] args) throws IOException {
        byte[] bo = new byte[100];
        String[] cmd = {"bash", "-c", "echo $PPID"};
        Process p = Runtime.getRuntime().exec(cmd);
        p.getInputStream().read(bo);
        System.out.println(new String(bo));
    }
    
    0 讨论(0)
  • 2020-12-06 06:19

    I tried (and failed) to do this a while back. I ended up wrapping my command in a shell script that dumped the pid to a file. Not the best solution but it got me past this hurdle.

    0 讨论(0)
  • 2020-12-06 06:24

    There is still no public API for this (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244896) but there are workarounds.

    A first workaround would be to use an external program like ps and to call it using Runtime.exec() to get the pid :)

    Another one is based on the fact that the java.lang.Process class is abstract and that you actually get a concrete subclass depending on your platform. On Linux, you'll get a java.lang.UnixProcess which has a private field int pid. Using reflection, you can easily get the value of this field:

    Field f = p.getClass().getDeclaredField("pid");
    f.setAccessible(true);
    System.out.println( f.get( p ) );
    
    0 讨论(0)
提交回复
热议问题