0

I need to get the PID of java.lang.Process to kill it after sometime. how to achieve this in JAVA.

{
  Process p = Runtime.getRuntime().exec("cmd /c start D:\\SBTool\\Test.bat");
}

I want to get the PID of process p. please help

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
user1058913
  • 321
  • 1
  • 4
  • 20
  • 1
    If you have the `Process`, you can kill it with the [destroy](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#destroy%28%29) method. No need to get the PID – jhamon Sep 23 '15 at 12:14
  • 2
    possible duplicate of [Killing a process using Java](http://stackoverflow.com/questions/6356340/killing-a-process-using-java) – Erik Pragt Sep 23 '15 at 12:18

1 Answers1

0

If you're using unix you can cast Process to UnixProcess and you will find the pid in that class
But if you're using windows you will need to to use the waitFor method, and then check if the exitCode is 0 if so you will need to read it using the buffer reader here's an example code:

    p.waitFor();
    if (p.exitValue()==0) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        return reader.readLine();
    }

However you don't need to use the pid to kill the process if that's what you're looking, There's a method inside the Process type that kill it for you

WaliedYassen
  • 65
  • 1
  • 10