Linux进程管理之结束与进程名称相匹配的进程(sh脚本)

简介:
原创作品,允许转载,转载时请务必以超链接形式标明文章  原始出处 、作者信息和本声明。否则将追究法律责任。 http://dgd2010.blog.51cto.com/1539422/1554623

在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

本文出自 “通信,我的最爱” 博客,请务必保留此出处http://dgd2010.blog.51cto.com/1539422/1554623

目录
相关文章
|
3天前
|
NoSQL Linux 程序员
【linux进程信号(一)】信号的概念以及产生信号的方式
【linux进程信号(一)】信号的概念以及产生信号的方式
|
3天前
|
Linux
【linux进程间通信(一)】匿名管道和命名管道
【linux进程间通信(一)】匿名管道和命名管道
|
3天前
|
Java Shell Linux
【linux进程控制(三)】进程程序替换--如何自己实现一个bash解释器?
【linux进程控制(三)】进程程序替换--如何自己实现一个bash解释器?
|
3天前
|
算法 Linux Shell
【linux进程(二)】如何创建子进程?--fork函数深度剖析
【linux进程(二)】如何创建子进程?--fork函数深度剖析
|
3天前
|
存储 Linux Shell
【linux进程(一)】深入理解进程概念--什么是进程?PCB的底层是什么?
【linux进程(一)】深入理解进程概念--什么是进程?PCB的底层是什么?
|
4天前
|
消息中间件 Unix Linux
Linux的学习之路:17、进程间通信(1)
Linux的学习之路:17、进程间通信(1)
18 1
|
4天前
|
存储 安全 Linux
Linux的学习之路:9、冯诺依曼与进程(1)
Linux的学习之路:9、冯诺依曼与进程(1)
18 0
|
4天前
|
Linux Shell Android开发
自动化脚本之GPIO/LED相关适用于Android/Linux
自动化脚本之GPIO/LED相关适用于Android/Linux
13 0
|
9天前
|
算法 Linux 调度
深入理解Linux内核的进程调度机制
【4月更文挑战第17天】在多任务操作系统中,进程调度是核心功能之一,它决定了处理机资源的分配。本文旨在剖析Linux操作系统内核的进程调度机制,详细讨论其调度策略、调度算法及实现原理,并探讨了其对系统性能的影响。通过分析CFS(完全公平调度器)和实时调度策略,揭示了Linux如何在保证响应速度与公平性之间取得平衡。文章还将评估最新的调度技术趋势,如容器化和云计算环境下的调度优化。
|
10天前
|
监控 Linux
linux监控指定进程
请注意,以上步骤提供了一种基本的方式来监控指定进程。根据你的需求,你可以选择使用不同的工具和参数来获取更详细的进程信息。
14 0