如何编写java程序获取pid

发布于 2024-07-16 19:16:04 字数 23 浏览 5 评论 0原文

如何编写java程序获取pid?

how to write java program get pid?

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

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

发布评论

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

评论(3

审判长 2024-07-23 19:16:04

Java 应用程序如何发现其进程 ID ( PID)

不是很简单,但显然没有“官方”方式。

How a Java Application Can Discover its Process ID (PID)

Not very straightforward, but apparently there is no "official" way.

路弥 2024-07-23 19:16:04

您可以使用 JMX 来完成此操作,但要小心。 以下不是官方支持的机制,可能会发生变化。 不过,我过去用过这个,而且效果很好。

RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
System.err.println("pid: " + rmxb.getName());

将打印 {pid}@hostname

You can do this using JMX, but beware. The below is not an officially supported mechanism and could change. However, I've used this in the past and it works fine.

RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
System.err.println("pid: " + rmxb.getName());

will print {pid}@hostname

人心善变 2024-07-23 19:16:04

我不相信这是 Java 提供的东西。 首先,它打破了平台无关的性质。 我可以看到两种方法来处理它,这两种方法都假设您在 UNIX 类型的系统下运行。

  • 提供一个 JNI,它将调用 getpid() 并返回它。
  • 使用系统或运行时方法之一来运行外部程序,该程序将调用 getppid() 来获取其父级(即 Java)的 PI​​D,或者更糟糕的情况,沿着进程树向上走,直到您找到Java本身。

I don't believe this is something Java supplies. For a start, it breaks the platform-independent nature. I can see two ways to approach it, both assuming you're running under a UNIX-type system.

  • provide a JNI which will call getpid() and return it.
  • use system or one of the Runtime methods to run an external program which will call getppid() to get the PID of its parent (i.e., Java), or worse case, walk up the process tree until you find Java itself.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文