2013-04-10 45 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

相關問題