Java 程序如何获得自己的进程 ID? [英] How can a Java program get its own process ID?

查看:18
本文介绍了Java 程序如何获得自己的进程 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取我的 Java 进程的 ID?

How do I get the id of my Java process?

我知道有几个依赖于平台的黑客,但我更喜欢更通用的解决方案.

I know there are several platform-dependent hacks, but I would prefer a more generic solution.

推荐答案

不存在可以保证在所有 jvm 实现中工作的独立于平台的方式.ManagementFactory.getRuntimeMXBean().getName() 看起来是最好(最接近)的解决方案,通常包括 PID.它很短,可能适用于各种广泛使用的实现.

There exists no platform-independent way that can be guaranteed to work in all jvm implementations. ManagementFactory.getRuntimeMXBean().getName() looks like the best (closest) solution, and typically includes the PID. It's short, and probably works in every implementation in wide use.

在 linux+windows 上,它返回一个类似于 12345@hostname 的值(12345 是进程 ID).请注意 根据文档,对此值没有任何保证:

On linux+windows it returns a value like 12345@hostname (12345 being the process id). Beware though that according to the docs, there are no guarantees about this value:

返回代表正在运行的 Java 虚拟机的名称.这返回的名称字符串可以是任意字符串和 Java 虚拟字符串机器实现可以选择嵌入特定平台有用的返回的名称字符串中的信息.每个正在运行的虚拟机可以有不同的名字.

Returns the name representing the running Java virtual machine. The returned name string can be any arbitrary string and a Java virtual machine implementation can choose to embed platform-specific useful information in the returned name string. Each running virtual machine could have a different name.

在 Java 9 中新的 进程 API 可以使用:

long pid = ProcessHandle.current().pid();

这篇关于Java 程序如何获得自己的进程 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆