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

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


当前回答

我发现了一个可能有点极端的解决方案,除了Windows 10之外,我没有在其他操作系统上尝试过,但我认为它值得注意。

如果您发现自己使用J2V8和nodejs,那么可以运行一个简单的javascript函数,返回java进程的pid。

这里有一个例子:

public static void main(String[] args) {
    NodeJS nodeJS = NodeJS.createNodeJS();
    int pid = nodeJS.getRuntime().executeIntegerScript("process.pid;\n");
    System.out.println(pid);
    nodeJS.release();
}

其他回答

我发现了一个可能有点极端的解决方案,除了Windows 10之外,我没有在其他操作系统上尝试过,但我认为它值得注意。

如果您发现自己使用J2V8和nodejs,那么可以运行一个简单的javascript函数,返回java进程的pid。

这里有一个例子:

public static void main(String[] args) {
    NodeJS nodeJS = NodeJS.createNodeJS();
    int pid = nodeJS.getRuntime().executeIntegerScript("process.pid;\n");
    System.out.println(pid);
    nodeJS.release();
}

这取决于你从哪里寻找信息。

如果要从控制台查找信息,可以使用jps命令。该命令的输出类似于Unix ps命令,并随JDK一起提供,因为我相信是1.5版本

如果从流程的角度来看,RuntimeMXBean(正如Wouter Coekaerts所说)可能是您的最佳选择。在使用Sun JDK 1.6 u7的Windows上,getName()的输出格式为[PROCESS_ID]@[MACHINE_NAME]。然而,你可以尝试执行jps并解析结果:

String jps = [JDK HOME] + "\\bin\\jps.exe";
Process p = Runtime.getRuntime().exec(jps);

如果运行时没有选项,输出应该是进程id后跟进程名。

我把这个加上其他解。

使用Java 10,获取进程id

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

以下是我的解决方案:

public static boolean isPIDInUse(int pid) {

        try {

            String s = null;
            int java_pid;

            RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
            java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf("@")));

            if (java_pid == pid) {
                System.out.println("In Use\n");
                return true;
            }
        } catch (Exception e) {
            System.out.println("Exception:  " + e.getMessage());
        }
        return false;
    }

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