“Kill a process tree” on windows using Java

白昼怎懂夜的黑 提交于 2019-12-01 05:46:56
Rajesh Kazhankodath

Finally got something workable even though its a roundabout way.

Apache Commons Exec API contains the CommandLauncher class that returns a java.lang.Process object. Thanks to the link

Here the link to get the windows Process Id from a java.lang.Process. This uses the JNA libraries.

Finally with the Process Id, here the command string that kills the process tree //String killCmd = "taskkill /F /T /PID " + JNAHandler.getPid(process);

Unfortunately, as you've discovered, there isn't a pure Java way of doing this. You'll have to resort to native commands or JNI libraries, all of which are platform-dependent and more complex than a pure Java solution would be.

It may be worth upvoting the relevant bug in the Java bug database: http://bugs.sun.com/view_bug.do?bug_id=4770092

With luck we can persuade the Java developers that the poor handling of subprocesses is worth fixing for Java 8.

As far as I know, there's no such option in commons-exec. It's not even possible to obtain the PID of whatever process you just started. You could trap the kill signal within your bash script, and have the handler kill the subprocess(es) when the script process is killed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!