重新创建已知 PID 的 Java 进程对象

huangapple go评论77阅读模式
英文:

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,如果需要的话可以进一步收集或操作,并且 ProcessHandle 处理与 Process 相同的操作(onExit()、destroy()、destroyForcibly() 等)。

英文:

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&lt;ProcessHandle&gt; 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.)

huangapple
  • 本文由 发表于 2020年10月14日 17:46:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64350659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定