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

4 comments:

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

    ReplyDelete
  2. I appreciate your genuine and heartfelt writing – thank you for your incredible blog and the inspiration it offers. Funny Shooter 2 offers a hilarious twist on FPS gaming. Discover the funniest enemies and powerful weapons in this unique shooter game!

    ReplyDelete
  3. Thank you for the time and effort you put into your blog. Your insightful posts have helped me on my journey toward self-improvement and growth. Find extra knowledge in this profile. Geo Dash Meltdown brings new levels and obstacles, pushing your reflexes as you jump to the beat of the music.

    ReplyDelete
  4. Thank you for creating a blog that inspires growth and positivity. It’s a valuable resource for anyone seeking guidance and motivation. Find useful ideas in this article. Geometry Dash Free takes platforming to a new level with vibrant, music-driven challenges.

    ReplyDelete