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

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


当前回答

您可以使用JNA。不幸的是,目前还没有通用的JNA API来获取当前的进程ID,但每个平台都非常简单:

窗户

确保你有jna-platform.jar然后:

int pid = Kernel32.INSTANCE.GetCurrentProcessId();

Unix

声明:

private interface CLibrary extends Library {
    CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class);   
    int getpid ();
}

然后:

int pid = CLibrary.INSTANCE.getpid();

Java 9

在Java 9中,新的进程API可用于获取当前进程ID。首先获取当前进程的句柄,然后查询PID:

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

其他回答

这是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源代码:

您可以使用JNA。不幸的是,目前还没有通用的JNA API来获取当前的进程ID,但每个平台都非常简单:

窗户

确保你有jna-platform.jar然后:

int pid = Kernel32.INSTANCE.GetCurrentProcessId();

Unix

声明:

private interface CLibrary extends Library {
    CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class);   
    int getpid ();
}

然后:

int pid = CLibrary.INSTANCE.getpid();

Java 9

在Java 9中,新的进程API可用于获取当前进程ID。首先获取当前进程的句柄,然后查询PID:

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

在Scala中:

import sys.process._
val pid: Long = Seq("sh", "-c", "echo $PPID").!!.trim.toLong

在Java 9发布之前,这将为您在Unix系统上提供一个变通方案。 (我知道,这个问题是关于Java的,但由于Scala没有相应的问题,所以我想把这个问题留给Scala用户,他们可能会遇到同样的问题。)

基于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平台上工作。

我把这个加上其他解。

使用Java 10,获取进程id

final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
final long pid = runtime.getPid();
out.println("Process ID is '" + pid);