Java:获取给定pid的进程

发布于 2024-09-28 16:18:22 字数 215 浏览 0 评论 0原文

假设我有一个已知的当前正在运行的进程,如何将其转换为 Java 中的 Process 对象? 该进程已经在运行,所以我不想生成另一个进程,我只想将其封装到一个可以在 java 代码中使用的 Process 对象中。 大致意思是:

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

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我只土不豪 2024-10-05 16:18:22

我认为仅使用内置库这是不可能的。 AFAIK,获取正在运行的进程自己的 PID 已经很不简单了(请参阅功能request替代机制)。

快速浏览一下 java.lang. lang.Process 表明您可以使用 JNI 和本机代码编写 java.lang.Process 的自定义实现。然后,您的自定义类可以实现额外的方法,例如您问题中的方法。

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.

旧伤还要旧人安 2024-10-05 16:18:22

在 *nix 世界中,获取非子进程的退出代码并不容易,因为一旦父进程获取了子进程的退出代码,退出代码就会与进程一起消失。您可以使用某些跟踪工具附加到正在运行的进程,并在进程终止时获取其退出代码。大多数 *nix 操作系统都有命令行工具,可以让您以非侵入式方式执行此操作(例如 Linux 上的 strace、SunOS 上的 truss)。但是,您只能在您自己的进程中或者以 root 身份运行时使用它们。另一种选择是配置操作系统的审核子系统来记录所有进程的退出代码。

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.

怪异←思 2024-10-05 16:18:22

你不能。 Process 中的每个操作都要求该进程是子进程。不是一个任意的过程。

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

节枝 2024-10-05 16:18:22

使用 RMI 怎么样?是否可以将 Process 对象传递给它所在的 Process?可能不是,因为进程不可序列化

what about using RMI? It it possible to pass a Process object to the Process which it is? Probably not, because Process is not Serializable

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文