Recreate Java Process Object from known PID

175 views Asked by At

I have a program (Process Monitor of some sort) that launches multiple programs with a ProcessBuilder. When I start this ProcessBuilder (for each program), I can start it and it will give me a Process object. With this Process object in memory, I can even stop my programs with destroy() or destroyForcibly().

Now, if my main program (Process Monitor) were to crash, and I restart it, and let's also say I have a the PID of each program I launched, how could I recreate a Process object with this PID ? I don't see the option in the Process class, or in ProcessBuilder (even though I guess we would need a ProcessLoader instead of a Builder).

Is there any way to do that?

To illustrate what I want:

long pid = getPid();
Process process = new Process(pid);
//or
Process process = new Process();
process.load(pid);
1

There are 1 answers

0
Lusheez On BEST ANSWER

So, if someone ever needs something like me, he can actually use ProcessHandle

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ProcessHandle.html

long pid = getPid();
ProcessHandle process;
Optional<ProcessHandle> possibleProcess = ProcessHandle.of(pid);
if(possibleProcess.isPresent()) process = possibleProcess.get();

You get a Stream than you can either collect or manipulate further if you wish, and a ProcessHandle handle the same set of operation as a Process (onExit(), destroy(), destroyForcibly(), etc.)