Get Subprocess Id in Java

How to get the pid of a Java subprocess?

Until Java 8 (included), you have to use workarounds.

From Java 9 onwards, there is a new getPid method in the Process class.

Get subprocess id in Java

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

Get process id from subprocess created by Thread

You can pass values between Threads using a Queue (https://docs.python.org/3/library/queue.html)
So pass a queue to your daemon thread, put the pid on the queue and retreive it in your main thread.

Get pid during long process with subprocess popen

The pid is available as soon as subprocess.Popen returns the objects, no need to wait.
Is the communicate function that wait the process to finish.

How get pid of a subprocess created with the same name of calling process?

Remove the break that terminates iteration. That way you will find all matching processes. Obviously you'll need to return a list of process IDs instead of a single one, but I presume you know how to do that.

how to get meta[container?] information by java subprocess pid

You can get more information about Java threads using jstack, but there is not way to get the application user ... in the sense that you are asking.

If you want to do that, then the application itself would need to implement a way to record this and output it on request.



Related Topics



Leave a reply



Submit