java 如何使用java关闭正在运行的进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10431452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to close running process using java?
提问by Sameek Mishra
I am using java Runtime.exec() method to execute bat file,in bat file i have write code that execute jar.This jar contain thread class that pooling infinite time the rabbitmq queue,if message are found then perform operation on that,mean the process will run infinite. i want to kill this process using java code,also i want know that can this method are able to execute shall script on Linux Os.
我正在使用 java Runtime.exec() 方法来执行 bat 文件,在 bat 文件中我编写了执行 jar 的代码。这个 jar 包含线程类,该线程类将无限时间池化rabbitmq 队列,如果找到消息,则对其执行操作,意思是该过程将无限运行。我想使用java代码终止这个进程,我也想知道这个方法是否能够在Linux操作系统上执行shall脚本。
**Used java code**
String myCMD = "cmd.exe /C start c:\elasticmgmtservice.bat";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(myCMD);
**used batch file**
cd c:
cd ElasticMgmtService\
java -jar ElasticIndexManagementService.jar config\ElasticIndexManagementService.xml
please help me to solve the problem.
请帮我解决问题。
采纳答案by Subhrajyoti Majumder
Runtime.exec(...) returns Process
object which consists following methods
Runtime.exec(...) 返回Process
包含以下方法的对象
- destroy()
- exitValue()
- getErrorStream()
- getInputStream()
- getOutputStream()
- waitFor()
- 破坏()
- 退出值()
- 获取错误流()
- 获取输入流()
- 获取输出流()
- 等待()
you can call destroy() which kills the subprocess. The subprocess represented by this Process object is forcibly terminated.
or you can kill by passing taskkill /PID <process id>
in Runtime.exec(...)
or kill -9 <process id>
你可以调用 destroy() 来杀死子进程。该 Process 对象所代表的子进程被强制终止。或者你可以通过杀死taskkill /PID <process id>
的Runtime.exec(...)
或kill -9 <process id>
回答by Diego D
In Windows
在 Windows 中
Runtime rt = Runtime.getRuntime();
rt.exec("taskkill " +<Your process>);
In Linux
在 Linux 中
Runtime rt = Runtime.getRuntime();
rt.exec("kill -9 " +<Your process>);
回答by Alexis Dufrenoy
Runtime.exec()
returns a Process object, which is an handler for the process the exec method has created. To kill this process, you have to call Process.destroy();
Runtime.exec()
返回一个 Process 对象,它是 exec 方法创建的进程的处理程序。要终止此进程,您必须调用Process.destroy();