英文:
Recreate Java Process Object from known PID
问题
我有一个程序(某种进程监视器),它使用ProcessBuilder启动多个程序。当我启动这个ProcessBuilder(针对每个程序),我可以启动它,然后它会给我一个Process对象。有了这个内存中的Process对象,我甚至可以使用destroy()或destroyForcibly()停止我的程序。
现在,如果我的主程序(进程监视器)崩溃了,并且我重新启动它,假设我还有我启动的每个程序的PID,我如何使用这个PID重新创建一个Process对象?我在Process类中没有看到这个选项,也没有在ProcessBuilder中看到(尽管我猜我们可能需要一个ProcessLoader而不是Builder)。
有没有任何方法可以做到这一点?
为了说明我想要的:
long pid = getPid();
Process process = new Process(pid);
// 或者
Process process = new Process();
process.load(pid);
英文:
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
得分: 1
所以,如果有人需要类似我的功能,实际上可以使用 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();
你可以获得一个 Stream
英文:
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<ProcessHandle> 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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论