2013-04-10 116 views
0

我有一个进程生成器,可以使某些进程在linux中工作(这段代码是由java编写的),但是在这些进程中,我想做一些中断来更改进程配置。如何使用Java中断Linux进程

如果我使用假脱机方法,它有太多的溢出所以我想用另一种方法来做一些中断到其他进程。

+0

http://stackoverflow.com/questions/4633678/how-to-kill-a-process-in-java-given-a-specific-pid检查了这一点。 – 2013-04-10 06:03:35

回答

3

由于@Vlad链接的答案是针对Windows,而这个问题是针对linux的,所以这里有一个答案。 Linux的uses signals to interrupt processes,您可以使用kill发出一个信号:

// shut down process with id 123 (can be ignored by the process) 
Runtime.getRuntime().exec("kill 123"); 
// shut down process with id 123 (can not be ignored by the process) 
Runtime.getRuntime().exec("kill -9 123"); 

用kill,您还可以发送其他信号作为man page告诉(和它没有成为一个杀人信号)。默认情况下,kill会发送一个SIGTERM信号,告诉进程终止,但可以忽略。如果您希望进程终止而不可忽略,则可以使用SIGKILL。在上面的代码中,第一次调用使用SIGTERM,后一次使用SIGKILL。您也可以显式地说明:

// shut down process with id 123 (can be ignored by the process) 
Runtime.getRuntime().exec("kill -SIGTERM 123"); 
// shut down process with id 123 (can not be ignored by the process) 
Runtime.getRuntime().exec("kill -SIGKILL 123"); 

如果你想和目标程序的名称,而不是进程ID进行操作,还有还有killall将接受的名称作为参数。顾名思义,这会杀死所有匹配的进程。例如:

// shuts down all firefox processes (can not be ignored) 
Runtime.getRuntime().exec("killall -SIGKILL firefox"); 
1

杀死进程使用下面的命令 ps -ef | grep 'process name' 使用PID杀掉进程其中pid是16804
例得到该进程的PID:

[[email protected] content]# ps -ef | grep tomcat 
root  16804  1 0 Apr09 ?  00:00:42 /usr/bin/java -Djava.util.logging.config.file=/usr/local2/tomcat66/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Xms1024m -Xmx1024m -/usr/local2/tomcat66/bin/bootstrap.jar -Dcatalina.base=/usr/local2/tomcat66 -Dcatalina.home=/usr/local2/tomcat66 -Djava.io.tmpdir=/usr/local2/tomcat66/temp org.apache.catalina.startup.Bootstrap start 

然后在java中使用命令

1. Runtime.getRuntime().exec("kill -15 16804"); // where -15 is SIGTERM 
or 
2. Runtime.getRuntime().exec("kill -9 16804"); // where -9 is SIGKILL 

检查这个各种Killing processes这对于killing signals

相关问题