Pages

Tuesday, January 31, 2012

Get the process id in java

Each application is treated as Process in our JVM. So how to get our running application in runtime. In java in lang package we are having a class called ManagementFactory. Which will help us to trace out process id of our running application.

     ManagementFactory.getRuntimeMXBean().getName()

It will returns the id in String format.
We need to use this command after each process or thread.
 
For Eg see the below examples: 
  
To Get the process id.  
import java.awt.BorderLayout;
import java.awt.Color;
import java.lang.management.ManagementFactory;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class SwingDemo {
     public static void main(String[] args) {
         try {
                JFrame f = new JFrame(System.nanoTime()+"");
                f.setSize(450, 450);
                f.setLocation(300,200);
                f.getContentPane().add(BorderLayout.CENTER, new JTextArea(10, 40));
                f.setVisible(true);
                f.setForeground(Color.BLUE);
              
                    //Process process = Runtime.getRuntime().exec("notepad.exe");
                    System.out.println("P id::=>" +
                                ManagementFactory.getRuntimeMXBean().getName()
                    );           
                    System.out.println("T id::=>" );
                    //    process.destroy();
            
             } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          
          }
}

To Kill the process id       

  // serviceName should be the process id  which we got from the above application.
  // taskkill /IM command will work on windows only. Check out in web for OS dependent commands.
  public static void killProcess(String serviceName) throws Exception {

          Runtime.getRuntime().exec("taskkill /IM " + serviceName);  
  }


To check whether Process is running or not.

  public static boolean isProcessRunning(String serviceName) throws Exception {

         Process p = Runtime.getRuntime().exec(TASKLIST);
         Thread.sleep(1000);
         BufferedReader reader = new BufferedReader(new InputStreamReader(
           p.getInputStream()));
         String line;
         while ((line = reader.readLine()) != null) {

          System.out.println("om ::"+ line);
          if (line.contains(serviceName)) {
           return true;
          }
         }

         return false;
}

So i hope with the help of above sample code you can achieve process id of your applications.

No comments:

Post a Comment