Killing a process using Java

前端 未结 8 1741
名媛妹妹
名媛妹妹 2020-11-22 11:08

I would like to know how to \"kill\" a process that has started up. I am aware of the Process API, but I am not sure, If I can use that to \"kill\" an already running proces

8条回答
  •  长发绾君心
    2020-11-22 12:00

    If you start the process from with in your Java application (ex. by calling Runtime.exec() or ProcessBuilder.start()) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.

    But be aware that if the process that you invoke creates new sub-processes, those may not be terminated (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092).

    On the other hand, if you want to kill external processes (which you did not spawn from your Java app), then one thing you can do is to call O/S utilities which allow you to do that. For example, you can try a Runtime.exec() on kill command under Unix / Linux and check for return values to ensure that the application was killed or not (0 means success, -1 means error). But that of course will make your application platform dependent.

提交回复
热议问题