Thursday, March 20, 2008

Getting UNIX process ID in Java

We encountered a need to kill process spawned by Runtime.getRuntime().exec() in java in a bit friendlier way than Process.destroy() provides for. To do this, easiest way is to execute "kill -number PID".
Process ID is not available as part of the interface, and below is outlined hack to get that information:

public class test
{
public static void main( String[] str )
{
try
{
Runtime r = Runtime.getRuntime() ;
Process p = r.exec( "sleep 200" ) ;
java.lang.reflect.Method m = p.getClass().getDeclaredMethod( "ac cess$100" , new Class[] { p.getClass() } ) ;
m.setAccessible(true);
Object ret = m.invoke( p , new Object[] { p } ) ;
System.out.println( "process ID " + ret ) ;
System.out.println( "Press Ctrl-Z and ps to confirm" ) ;
Thread.sleep( 100000 ) ;
}
catch( Exception e )
{
e.printStackTrace() ;
}
System.exit(1);
}

}