Saturday, July 27, 2013

Start a program using Linux Commands from Java & get its Process ID

Get Process ID of Linux Process that started using Java (Runtime.getRuntime().exec(command))


Hi my friends, we know how to start a sub-program from java using Runtime.getRuntime().exec(command). But how to get process id ?

Here is the answer,


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.UnixProcesswhich has a private field int pid.



Process proc = Runtime.getRuntime().exec(command);
Field f = proc.getClass().getDeclaredField("pid");
f.setAccessible(true);
System.out.println("Process ID : " + f.get(proc));


Example :


import java.lang.reflect.Field;

public class TestCMD {
 public static void main(String[] args) {
  String cmd = "echo HelloAll";
  int processId = execute(cmd);
  System.out.println("Process ID : " + processId);
 }

 private static int execute(String command) {
  int pid = 0;
  try {
   Process proc = Runtime.getRuntime().exec(command);
   Field f = proc.getClass().getDeclaredField("pid");
   f.setAccessible(true);
   pid = (int) f.get(proc);

  } catch (Exception e) {

   e.printStackTrace();
  }
  return pid;
 }
}

1 comment:

  1. It's really good solution for Unix based systems, works well.
    Thanks.

    ReplyDelete

Total Pageviews

Translate