如何获得我的Java进程的id ?

我知道有一些平台相关的黑客,但我更喜欢一个更通用的解决方案。


当前回答

java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split("@")[0]

其他回答

我最新发现的是有一个系统属性叫做sun.java.launcher.pid,至少在linux上是可用的。我的计划是使用它,如果没有发现它使用JMX bean。

这是我有类似需求时使用的。这将正确地确定Java进程的PID。让您的java代码在预定义的端口号上生成服务器,然后执行操作系统命令找出在端口上侦听的PID。Linux

netstat -tupln | grep portNumber

您可以尝试在JNR-Posix中的getpid()。

它有一个Windows POSIX包装器,从libc调用getpid()。

基于Ashwin Jayaprakash的答案(+1) 关于Apache 2.0许可的SIGAR,下面是我如何使用它来获得当前进程的PID:

import org.hyperic.sigar.Sigar;

Sigar sigar = new Sigar();
long pid = sigar.getPid();
sigar.close();

尽管它不能在所有平台上工作,但它可以在Linux、Windows、OS X和这里列出的各种Unix平台上工作。

这是JConsole,可能还有jps和VisualVM使用的代码。它利用类 sun.jvmstat.monitor。* tool.jar中的包

package my.code.a003.process;

import sun.jvmstat.monitor.HostIdentifier;
import sun.jvmstat.monitor.MonitorException;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;


public class GetOwnPid {

    public static void main(String[] args) {
        new GetOwnPid().run();
    }

    public void run() {
        System.out.println(getPid(this.getClass()));
    }

    public Integer getPid(Class<?> mainClass) {
        MonitoredHost monitoredHost;
        Set<Integer> activeVmPids;
        try {
            monitoredHost = MonitoredHost.getMonitoredHost(new HostIdentifier((String) null));
            activeVmPids = monitoredHost.activeVms();
            MonitoredVm mvm = null;
            for (Integer vmPid : activeVmPids) {
                try {
                    mvm = monitoredHost.getMonitoredVm(new VmIdentifier(vmPid.toString()));
                    String mvmMainClass = MonitoredVmUtil.mainClass(mvm, true);
                    if (mainClass.getName().equals(mvmMainClass)) {
                        return vmPid;
                    }
                } finally {
                    if (mvm != null) {
                        mvm.detach();
                    }
                }
            }
        } catch (java.net.URISyntaxException e) {
            throw new InternalError(e.getMessage());
        } catch (MonitorException e) {
            throw new InternalError(e.getMessage());
        }
        return null;
    }
}

这里有几个问题:

The tool.jar is a library distributed with Oracle JDK but not JRE! You cannot get tool.jar from Maven repo; configure it with Maven is a bit tricky The tool.jar probably contains platform dependent (native?) code so it is not easily distributable It runs under assumption that all (local) running JVM apps are "monitorable". It looks like that from Java 6 all apps generally are (unless you actively configure opposite) It probably works only for Java 6+ Eclipse does not publish main class, so you will not get Eclipse PID easily Bug in MonitoredVmUtil?

更新:我刚刚再次检查了JPS使用这种方式,即Jvmstat库(tool.jar的一部分)。因此,不需要调用JPS作为外部进程,直接调用Jvmstat库,如我的示例所示。你也可以通过这种方式获取在本地主机上运行的所有jvm的列表。 参见JPS源代码: