java 如何编写java程序获取pid

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/750660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:37:35  来源:igfitidea点击:

how to write java program get pid

javaprocesspid

提问by paxdiablo

how to write java program get pid?

如何编写java程序获取pid?

回答by Thilo

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

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

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

不是很直接,但显然没有“官方”的方式。

回答by Brian Agnew

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.

您可以使用 JMX 执行此操作,但要小心。以下不是官方支持的机制,可能会更改。但是,我过去使用过它并且效果很好。

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

will print {pid}@hostname

将打印 {pid}@hostname

回答by paxdiablo

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.

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

  • 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.
  • 提供一个 JNI,它将调用getpid()并返回它。
  • 使用 system 或 Runtime 方法之一来运行外部程序,该程序将调用getppid()以获取其父级(即 Java)的 PI​​D,或者更糟的情况是,沿着进程树向上走,直到找到 Java 本身。