在Linux系统中经常会遇到结束某个进程的情况,一般我们会使用kill、pkill、killall甚至top这样的工具结束进程,但这些工具虽然是结束进程的基本工具,但使用起来要接进程名全名或准确的pid。下文提供的脚本可以结束与指定的进程名称相匹配的任意进程(杀死指定名称的进程),如果匹配的pid有两个及其以上,kill也能处理掉,设计这个功能的工程师实在是太高明了!赞!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
#!/bin/bash
pname=$1
puser=$2
if
[[ -z $pname ]];
then
echo
"Fatal error, you MUST assign a process name"
exit
1
fi
if
[[
"$1"
==
"-h"
||
"$1"
==
"--help"
]];
then
echo
"Func: This shell script will find the process you want to kill with signal 9, process name support regular expression with 'grep'\n"
echo
"Usage: $0 processname\n"
echo
"Example: $0 run, this will kill all process which match 'run'\n"
exit
0
fi
if
[[ -z $puser ]];
then
puser=root
fi
pid=`
ps
aux |
grep
$pname |
grep
$puser |
grep
-
v
grep
|
awk
'{print $2}'
`
if
[[ -z $pid ]];
then
echo
":(, I can NOT find $pname running by $puser"
fi
# There maybe exist bugs refer to $pid have more than one pid, such as 2 or more
# So there is a TODO to fix it,
# But kill utility support kill pids which more than one, :)
kill
-9 $pid >
/dev/null
2>&1
# eof
# because of kill will exit automatically
reval=$?
vpid=`
ps
aux |
grep
$pname |
grep
$puser |
grep
-
v
grep
|
awk
'{print $2}'
`
if
[[ -z $vpid && $reval -
eq
0 ]];
then
echo
":(, Failed, I can NOT kill $pname running by $puser, got an error code $reval"
else
echo
":), Successfully,I killed $pname running by $puser"
fi
|
测试用脚本,此脚本会借助nohup this >/dev/null 2>&1 & 一直运行,this表示你想命名的名字,别忘了chmod +x this。
1
2
3
4
5
6
|
#!/bin/bash
while
:
do
#sleep 2 second
usleep 2000
done
|
end
本文转自 urey_pp 51CTO博客,原文链接:http://blog.51cto.com/dgd2010/1554623,如需转载请自行联系原作者