代码之家  ›  专栏  ›  技术社区  ›  Pawka

获取Java中的子进程id

  •  13
  • Pawka  · 技术社区  · 16 年前

    String command = new String("some_program");
    
    Process p = Runtime.getRuntime().exec(command);
    

    如何获取子进程id?

    另外,我在Linux上工作。

    4 回复  |  直到 16 年前
        1
  •  28
  •   Pascal Thivent    16 年前

    仍然没有用于此的公共API(请参阅 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244896 )但也有解决办法。

    第一个解决方法是使用外部程序,如 ps Runtime.exec() 要获取pid:)

    另一个是基于以下事实: java.lang.Process java.lang.UnixProcess 它有一个私人领域 int pid . 使用反射,您可以轻松获得此字段的值:

    Field f = p.getClass().getDeclaredField("pid");
    f.setAccessible(true);
    System.out.println( f.get( p ) );
    
        2
  •  1
  •   Martin    16 年前

    不久前我尝试过(但失败了)。最后,我将命令包装在一个shell脚本中,该脚本将pid转储到一个文件中。这不是最好的解决办法,但它让我克服了这个障碍。

        3
  •  1
  •   Francis Upton IV    16 年前

        4
  •  1
  •   Bozho    16 年前

    从…起 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));
    }