在 Java 中获取子进程 ID [英] Get subprocess id in Java

查看:49
本文介绍了在 Java 中获取子进程 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以这种方式创建子流程:

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?

附言我在 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 这样的外部程序,并使用 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 类是抽象的,并且您实际上会根据您的平台获得一个具体的子类.在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆