How do you get the process id in java?

I am trying to find a way to programmatically open and close an application. I easily run the application using

Runtime.getRuntime().exec(new String[] {"open", "<path to application>"}); 

however, the only way I can close it is to use the line

  Runtime.getRuntime().exec(new String[] {"kill", "<process id#>"}); 

and I still can’t find the identifier #, except manually opening the terminal, and use the top one to find #. If there is a programmatic way to get this identifier or just the best way to open and close applications, I would like to hear about it.

thanks

+4
source share
2 answers

Use java.lang.ProcessBuilder to start the subprocess. The returned Process object has a destroy() method that allows you to kill it.

+3
source

This probably no longer applies to the original poster (due to the elapsed time), but only for the sake of completeness ...

You get the handle to the process object as a result of the exec(...) command:

 Process myProcess = Runtime.getRuntime().exec("mybin"); 

Then you can kill at any time with destroy() :

 myProcess.destroy(); 

Note. This may be similar to what Jim described, but not using ProcessBuilder .

0
source

Source: https://habr.com/ru/post/1334306/


All Articles