如何获得我刚刚在java程序中启动的进程的PID? [英] How to get PID of process I've just started within java program?

查看:216
本文介绍了如何获得我刚刚在java程序中启动的进程的PID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用以下代码开始了一个过程

I've started a process with following code

 ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path");
 try {
     Process p = pb.start();       
 } 
 catch (IOException ex) {}

现在我需要知道我刚刚开始的进程的pid。

Now I need to know the process's pid that I've just started.

推荐答案

目前还没有公共API。请参阅Sun 错误4244896 ,Sun 错误4250622

There is no public API for this yet. see Sun Bug 4244896, Sun Bug 4250622

作为解决方法:

Runtime.exec(...)

返回类型为

java.lang.Process

Process类是抽象的,你得到的是Process的一些子类,它是为你的操作系统设计的。例如,在Mac上,它返回 java.lang.UnixProcess ,它有一个名为 pid 的私有字段。使用Reflection,您可以轻松获得此字段的值。这无疑是一个黑客,但它可能会有所帮助。无论如何你还需要 PID

The Process class is abstract, and what you get back is some subclass of Process which is designed for your operating system. For example on Macs, it returns java.lang.UnixProcess which has a private field called pid. Using Reflection you can easily get the value of this field. This is admittedly a hack, but it might help. What do you need the PID for anyway?

这篇关于如何获得我刚刚在java程序中启动的进程的PID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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