开发者

How can you fetch the id of a process in java?

Ho开发者_运维问答w do I fetch the id of a process spawned by Runtime.getRuntime().exec?


This is going to be environment/OS specific.

If you're on Unix, you can write a script to output the process id, and then exec to execute your required process. That process will replace the script in the process table and run with the same process id. e.g.

#!/bin/sh
echo $$
exec 'your program here'

So your parent Java process can spawn this, read the output, and the first line is your process id.


Edit - As Brian pointed this get's the id of the running process and not of the spawned one.

First solution that i can think of, would be something like:

ManagementFactory.getRuntimeMXBean().getName();

And you'll get something like: 18306@localhost. 18306 is the process id.


There's an API which allows you to query the process list from java: Sigar. It looks commercial but it's actually GPL. If you have some details about your spawned process you might be able to whip up a Sigar query which will return you the pid.

This is cross-platform.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜