linux杀死进程方法总结

总结不同杀死进程的方法,适用于各种情况

Posted by shay on October 16, 2020

常规篇:

首先,用ps查看进程,方法如下:

$ ps -ef

smx 1822 1 0 11:38 ? 00:00:49 gnome-terminal smx 1823 1822 0 11:38 ? 00:00:00 gnome-pty-helper smx 1824 1822 0 11:38 pts/0 00:00:02 bash

或者:

$ ps -aux

smx 1822 0.1 0.8 58484 18152 ? Sl 11:38 0:49 gnome-terminal smx 1823 0.0 0.0 1988 712 ? S 11:38 0:00 gnome-pty-helper smx 1824 0.0 0.1 6820 3776 pts/0 Ss 11:38 0:02 bash

此时如果我想杀了火狐的进程就在终端输入:

$ kill -s 9 1827

其中-s 9 制定了传递给进程的信号是9,即强制、尽快终止进程。各个终止信号及其作用见附录。

1827则是上面ps查到的火狐的PID。

简单吧,但有个问题,进程少了则无所谓,进程多了,就会觉得痛苦了,无论是ps -ef 还是ps -aux,每次都要在一大串进程信息里面查找到要杀的进程,看的眼都花了。

进阶篇:

改进1:

把ps的查询结果通过管道给grep查找包含特定字符串的进程。管道符“|”用来隔开两个命令,管道符左边命令的输出会作为管道符右边命令的输入。

**$ ps -ef grep firefox**

smx 1827 1 4 11:38 ? 00:27:33 /usr/lib/firefox-3.6.18/firefox-bin smx 12029 1824 0 21:54 pts/0 00:00:00 grep –color=auto firefox

这次就清爽了。然后就是

$kill -s 9 1827

还是嫌打字多?

改进2——使用pgrep:

一看到pgrep首先会想到什么?没错,grep!pgrep的p表明了这个命令是专门用于进程查询的grep。

$ pgrep firefox 1827

看到了什么?没错火狐的PID,接下来又要打字了:

$kill -s 9 1827

改进3:

知道pgrep和pidof两个命令,干嘛还要打那么长一串! $ pgrep firefox | xargs kill -s 9

改进4:

ps -ef | grep firefox | awk ‘{print2}’ | xargs kill -9

kill: No such process 有一个比较郁闷的地方,进程已经正确找到并且终止了,但是执行完却提示找不到进程。

其中awk ‘{print $2}’ 的作用就是打印(print)出第二列的内容。根据常规篇,可以知道ps输出的第二列正好是PID。就把进程相应的PID通过xargs传递给kill作参数,杀掉对应的进程。

改进5:

难道每次都要调用xargs把PID传递给kill?答案是否定的:

kill -s 9 ps -aux | grep firefox | awk '{print2}'

改进6——pkill:

看到pkill想到了什么?没错pgrep和kill!pkill=pgrep+kill。

$pkill -9 firefox

说明:”-9” 即发送的信号是9,pkill与kill在这点的差别是:pkill无须 “s”,终止信号等级直接跟在 “-“ 后面。之前我一直以为是 “-s 9”,结果每次运行都无法终止进程。

改进7——killall:

killall和pkill是相似的,不过如果给出的进程名不完整,killall会报错。pkill或者pgrep只要给出进程名的一部分就可以终止进程。

$killall -9 firefox


附录:各种信号及其用途

SignalDescriptionSignal number on Linux x86[1]
SIGABRTProcess aborted6
SIGALRMSignal raised by alarm14
SIGBUSBus error: "access to undefined portion of memory object"7
SIGCHLDChild process terminated, stopped (or continued*)17
SIGCONTContinue if stopped18
SIGFPEFloating point exception: "erroneous arithmetic operation"8
SIGHUPHangup1
SIGILLIllegal instruction4
SIGINTInterrupt2
SIGKILLKill (terminate immediately)9
SIGPIPEWrite to pipe with no one reading13
SIGQUITQuit and dump core3
SIGSEGVSegmentation violation11
SIGSTOPStop executing temporarily19
SIGTERMTermination (request to terminate)15
SIGTSTPTerminal stop signal20
SIGTTINBackground process attempting to read from tty ("in")21
SIGTTOUBackground process attempting to write to tty ("out")22
SIGUSR1User-defined 110
SIGUSR2User-defined 212
SIGPOLLPollable event29
SIGPROFProfiling timer expired27
SIGSYSBad syscall31
SIGTRAPTrace/breakpoint trap5
SIGURGUrgent data available on socket23
SIGVTALRMSignal raised by timer counting virtual time: "virtual timer expired"26
SIGXCPUCPU time limit exceeded24
SIGXFSZFile size limit exceeded25

修改于他人博客