giri
giri

Reputation: 27229

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

How do I fetch the id of a process spawned by Runtime.getRuntime().exec?

Upvotes: 2

Views: 251

Answers (3)

Joeri Hendrickx
Joeri Hendrickx

Reputation: 17445

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.

Upvotes: 0

Adrian Fâciu
Adrian Fâciu

Reputation: 12562

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.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272397

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.

Upvotes: 1

Related Questions