Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get subprocess id in Java

I'm creating subprocesses in this way:

String command = new String("some_program");

Process p = Runtime.getRuntime().exec(command);

How I can get that subprocess id?

P.S. I'm working on Linux.

like image 623
Pawka Avatar asked Dec 13 '09 20:12

Pawka


People also ask

How do I find JVM 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 can one get current process ID in Java?

getRuntimeMXBean(). getPid() method to get the process ID. This method returns the process ID representing the running Java virtual machine.

How can I get the process ID of Java application in Linux?

Fig: 'ps' command displaying all Java processes running on Linux machine. The red color highlight in the above figure indicates the process IDs of all Java processes running on this EC2 instance. From here, you can get hold of your application's process ID.

How do I view a Java process in Windows?

Use Windows Task manager, go to 'processes' tab to locate your java process and get the process id. If the process id column does not show up, you will have to click on 'View -> Add Columns' and select PID.


2 Answers

There is still no public API for this (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244896) but there are workarounds.

A first workaround would be to use an external program like ps and to call it using Runtime.exec() to get the pid :)

Another one is based on the fact that the java.lang.Process class is abstract and that you actually get a concrete subclass depending on your platform. On Linux, you'll get a java.lang.UnixProcess which has a private field int pid. Using reflection, you can easily get the value of this field:

Field f = p.getClass().getDeclaredField("pid");
f.setAccessible(true);
System.out.println( f.get( p ) );
like image 177
Pascal Thivent Avatar answered Oct 13 '22 19:10

Pascal Thivent


I tried (and failed) to do this a while back. I ended up wrapping my command in a shell script that dumped the pid to a file. Not the best solution but it got me past this hurdle.

like image 20
Martin Avatar answered Oct 13 '22 18:10

Martin