Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the process ID (pid) of a process started in java? [duplicate]

Tags:

java

process

pid

If I get a process object in Java through Runtime.getRuntime().exec(...), or ProcessBuilder.start(), I can wait for it through Process.waitFor(), which is like Thread.join(), or I could kill it with Process.destroy(), which is like the deprecated Thread.stop().

BUT: How do I find the pid of the Process Object? I don't see a method for doing that in The Official Documentation. Can I do this in Java? If so, how?

like image 755
Leo Izen Avatar asked Mar 12 '11 17:03

Leo Izen


People also ask

How do I find the Java process ID?

You can use the jps utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class. jps tool is now included in JDK/bin directory.

How do I find process ID for running process?

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column.

How do I find the Java process ID in Linux?

On Linux, you can view processes with the ps command. It is the simplest way to view the running processes on your system. You can use the ps command to view running Java processes on a system also by piping output to grep .

Is process PID unique?

Short for process identifier, a PID is a unique number that identifies each running processes in an operating system, such as Linux, Unix, macOS, and Microsoft Windows.


2 Answers

This guy calls out to bash to get the PID. I'm not sure if there is an java solution to the problem.

/**
 * Gets a string representing the pid of this program - Java VM
 */
public static String getPid() throws IOException,InterruptedException {

  Vector<String> commands=new Vector<String>();
  commands.add("/bin/bash");
  commands.add("-c");
  commands.add("echo $PPID");
  ProcessBuilder pb=new ProcessBuilder(commands);

  Process pr=pb.start();
  pr.waitFor();
  if (pr.exitValue()==0) {
    BufferedReader outReader=new BufferedReader(new InputStreamReader(pr.getInputStream()));
    return outReader.readLine().trim();
  } else {
    System.out.println("Error while getting PID");
    return "";
  }
}

Source: http://www.coderanch.com/t/109334/Linux-UNIX/UNIX-process-ID-java-program

like image 174
nsfyn55 Avatar answered Oct 09 '22 15:10

nsfyn55


Similar to the other tools mentioned, there is the jps command line tool that comes with the Java runtime. It spits out the PIDs of all running JVMs. The benefit is the output one needs to parse is confined to only the JVM processes.

like image 39
Brent Worden Avatar answered Oct 09 '22 17:10

Brent Worden