How do you get a process id in java?
I am trying to find a way to programmaticaly open and close an application. I can launch the application easily using
Runtime.getRuntime().exec(new String[] {"open", "<path to application>"});
however, the only way I can find to close it is to use the line
Runtime.getRuntime().exec(new String[] {"kill", "<process id#>"});
and I can't find anyway to get the id # other than manually opening terminal and using top to find the #. If there is a programmatic way to get this id, or just a better way to go about opening and cl开发者_Go百科osing applications i would love to hear about it.
Thanks
Use a java.lang.ProcessBuilder
to start the subprocess. The returned Process
object has a destroy()
method which will let you kill it.
This probably isn't relevant anymore to the original poster (due to the elapsed time) but just for the sake of completeness...
You get a handle to the process object as a result of the exec(...)
command:
Process myProcess = Runtime.getRuntime().exec("mybin");
You can then kill at any later time with destroy()
:
myProcess.destroy();
Note: This might be similar to what Jim was describing but not using the ProcessBuilder
.
精彩评论