tags:

views:

63

answers:

3

Say I have a current running process known, how can I turn this into a Process object in Java? The process is already running, so I don't want to spawn off another one, I just want to encapsulate it into a Process object that I can use within the java code. Something along the lines of:

int pid = getPid();
Process proc = magicGetProcess(pid);

thanks

+1  A: 

I don't think this is possible using only the builtin library. AFAIK, it is already non-trivial to get the running process' own PID (see the feature request and alternate mechanisms).

A quick look at the java.lang.Process class shows that you could go about writing your custom implementation of java.lang.Process using JNI and native code. Your custom class could then implement extra methods, such as the one in your question.

André Caron
Hmm ya that is what it looks like. Oh well.
Th3sandm4n
A: 

In *nix world grabbing exit code of a non-child process is not easy, because the exit code simply disappears together with the process as soon as the parent process has picked up the exit code of the child. You can attach to the running process using some tracing tool and pick up its exit code when the process dies. Most *nix OSes have command line tools which will let you do it (such as strace on Linux, truss on SunOS) in a non-intrusive way. However, you can only use them against your own processes or if you run as root. Another alternative is to configure audit subsystem of your OS to record exit codes of all processes.

abb
On Unix you can use the `waitpid()` function to grab the exit code of a non-child process. The problem is calling it from Java.
Alexandre Jasmin
A: 

You can't. Every operation in Process requires that the process is a child process. Not an arbitrary process.

EJP