我的測試機中有個進程,使用一般的kill命令殺不掉,如下:
[root]tmelinux02# ps aux | grep mongoose /root
root 13950 0.0 0.0 112712 964 pts/0 S+ 03:56 0:00 grep --color=auto mongoose
root 25872 42.0 3.0 48474464 9917640 ? SNl May18 9691:38 /opt/mongoose/jdk-11.0.5+10-jre/bin/java -jar /opt/mongoose/mongoose-bundle-4.2.15.jar --run-node
[root]tmelinux02# kill 25872 /root
[root]tmelinux02# ps aux | grep mongoose /root
root 13989 0.0 0.0 112712 968 pts/0 S+ 03:57 0:00 grep --color=auto mongoose
root 25872 42.0 3.0 48474464 9917852 ? SNl May18 9691:39 /opt/mongoose/jdk-11.0.5+10-jre/bin/java -jar /opt/mongoose/mongoose-bundle-4.2.15.jar --run-node
於是使用了“kill -9”這一招,成功殺掉了進程。
[root]tmelinux02# kill -9 25872 /root
[root]tmelinux02# ps aux | grep mongoose /root
root 14166 0.0 0.0 112712 964 pts/0 S+ 03:58 0:00 grep --color=auto mongoose
那么kill –9 跟 普通的kill有什么不同呢?
Kill命令會發送一個信號(signal)給指定的進程或一批進程。如果不指定任何信號(signal),那么默認就會發送TERM這個信號。如果信號進程接不到,比如已經hang住了,那么可以使用9這個信號來強制殺掉進程。
幾個有用的信號的英文原版的解釋:
- SIGINT - This signal is the same as pressing ctrl-c. On some systems, "delete" + "break" sends the same signal to the process. The process is interrupted and stopped. However, the process can ignore this signal.
- SIGTERM - This signal requests a process to stop running. This signal can be ignored. The process is given time to gracefully shutdown. When a program gracefully shuts down, that means it is given time to save its progress and release resources. In other words, it is not forced to stop. SIGINT is very similar to SIGTERM.
- SIGKILL - The SIGKILL signal forces the process to stop executing immediately. The program cannot ignore this signal. This process does not get to clean-up either.
- SIGSTOP - This signal makes the operating system pause a process's execution. The process cannot ignore the signal.
- SIGCONT - To make processes continue executing after being paused by the SIGTSTP or SIGSTOP signal, send the SIGCONT signal to the paused process. This is the CONTinue SIGnal. This signal is beneficial to Unix job control (executing background tasks).
注意,下面這三個命令作用是一樣的。
kill -9 1234
kill -KILL 1234
kill -SIGKILL 1234
值得注意的是kill –9, 即SIGKILL,不是發給進程的,而是發給操作系統的。當你指定了kill –9的時候,你並不是告訴應用程序讓它自己停止下來,而是告訴操作系統干掉這個應用程序,甭管它現在正在干啥,殺就完了。這就是我們為什么我們開頭殺不掉的進程,用kill –9 卻可以殺掉的原因。
另一個發給操作系統的信號是SIGSTOP,只不過,SIGSTOP不會殺掉進程,而是凍結住進程的執行,你可以使用SIGCONT來在稍后對這個進程進行恢復。而這一切應用程序完全不知情。
參考資料
================
What is the purpose of the -9 option in the kill command?
Kill Commands and Signals
https://www.linux.org/threads/kill-commands-and-signals.8881/