在Java中获取子进程ID [英] Get subprocess id in Java
问题描述
我正在以这种方式创建子进程:
I'm creating subprocesses in this way:
String command = new String("some_program");
Process p = Runtime.getRuntime().exec(command);
我如何获得该子流程ID?
How I can get that subprocess id?
PS我正在使用Linux。
P.S. I'm working on Linux.
推荐答案
此处仍然没有公共API(参见 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244896 )但有解决方法。
There is still no public API for this (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244896) but there are workarounds.
第一种解决方法是使用外部程序,如 ps
并使用<$ c来调用它$ c> Runtime.exec()获取pid:)
A first workaround would be to use an external program like ps
and to call it using Runtime.exec()
to get the pid :)
另一个是基于 java.lang.Process
class是抽象的,你实际上根据你的平台获得了一个具体的子类。在Linux上,你将得到一个 java.lang.UnixProcess
,它有一个私有字段 int 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 ) );
这篇关于在Java中获取子进程ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!