Home > other >  How can I get the PID of my Java application at runtime?
How can I get the PID of my Java application at runtime?

Time:09-22

I am running a simple Java application as follows:

class MyApp 
{
    public static void main(String[] args) 
    {
        // Do stuff
    }
}

Now I want to get the process ID (PID) of this application from inside my main() function so that I can save it to a file. How can I do that in a platform-independent way?


EDIT: The existing solutions on Stackoverflow are many years old and probably better solutions exist today. This is why I'm asking this question.


EDIT 2: I would prefer solutions that do NOT require Java 9.

CodePudding user response:

My operating environment is jdk6

import java.lang.management.ManagementFactory;
public static void main(String[] args) {
    String name = ManagementFactory.getRuntimeMXBean().getName();
    System.out.print(name.split("@")[0]);
}

CodePudding user response:

Use RuntimeMXBean

RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
long pid = runtime.getPid();

CodePudding user response:

You can get PID by following

ManagementFactory.getRuntimeMXBean().getSystemProperties().get("PID")

Or

System.getProperty("PID");
  • Related