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

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


当前回答

以下是我的解决方案:

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;
    }

其他回答

自Java 9以来,有一个方法process . getpid(),它返回进程的本机ID:

public abstract class Process {

    ...

    public long getPid();
}

要获取当前Java进程的进程ID,可以使用ProcessHandle接口:

System.out.println(ProcessHandle.current().pid());

您可以使用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();

为完整起见,Spring Boot中有一个用于

String jvmName = ManagementFactory.getRuntimeMXBean().getName();
return jvmName.split("@")[0];

解决方案。如果需要一个整数,那么可以将其总结为一行代码:

int pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);

如果有人已经使用了Spring引导,她/他可能会使用org.springframework.boot.ApplicationPid

ApplicationPid pid = new ApplicationPid();
pid.toString();

toString()方法输出pid或'?? '。

使用ManagementFactory的注意事项已经在其他回答中讨论过了。

在Scala中:

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

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

对于旧的JVM,在linux中…

private static String getPid() throws IOException {
    byte[] bo = new byte[256];
    InputStream is = new FileInputStream("/proc/self/stat");
    is.read(bo);
    for (int i = 0; i < bo.length; i++) {
        if ((bo[i] < '0') || (bo[i] > '9')) {
            return new String(bo, 0, i);
        }
    }
    return "-1";
}