1

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.

user5123481566
  • 53
  • 1
  • 10
  • which jdk version you use? –  Sep 22 '21 at 08:56
  • 1
    Better solutions do exist now. But they require java 9. The linked answer is the best you’ll get for java 8 - they haven’t been making lots of changes to it. – BeUndead Sep 22 '21 at 08:58
  • 2
    so you want a newer solution, but you don't want to use a newer jdk? what makes you think newer solutions will work if you don't update your jdk? – Stultuske Sep 22 '21 at 08:58
  • Also, depending on how you’re starting the program, it might be simpler to just write to the file as you start it. https://serverfault.com/questions/205498/how-to-get-pid-of-just-started-process Something like that, but piped to a file. – BeUndead Sep 22 '21 at 09:01
  • Heres a similiar question: https://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id – Andreas Sekkingstad Sep 22 '21 at 09:03

3 Answers3

3

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]);
}
Nelson L
  • 31
  • 2
1

Use RuntimeMXBean

RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
long pid = runtime.getPid();
Dhruv Singh
  • 2,185
  • 2
  • 11
  • 17
0

You can get PID by following

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

Or

System.getProperty("PID");

enter image description here

Abdur Rahman
  • 1,420
  • 1
  • 21
  • 32