获取进程号并赋值判断进程状态 -尊龙游戏旗舰厅官网
一、
pgrep 是通过程序的名字来查询进程的工具,一般是用来判断程序是否正在运行。在服务器的配置和管理中,这个工具常被应用,简单明了。
用法:
#pgrep [选项] [程序名]
pgrep [-flvx][-n |-o][-d delim][-p ppidlist][-g pgrplist][-s sidlist][-u euidlist][-u uidlist][-g gidlist][-j projidlist][-t termlist][-t taskidlist][-c ctidlist][-z zoneidlist][pattern]
常用参数
-l 列出程序名和进程id;
-o 进程起始的id;
-n 进程终止的id;
另外,还可以使用另外一个ps命令:(点击查看ps命令详解)
ps x | grep xxx | awk '{print $1}'
实例:
ps x | grep java | awk '{print $1}'
注释:
1、xxx为执行的命令名称
2、举个例子,获取当前用户下的java进程 【pid】
[admin@vm168a ~]$ ps x | grep java | awk ?'{print $1}'
16920
3、用到三个命令,ps、grep、awk。
要是这样获取不到的话,可以使用ps命令:
ps -ef | grep xxx | grep -v 'grep'| awk '{print $2}'
[yanue@server ~]$ ps -ef | grep nginx | grep -v 'grep'| awk '{print $2}'
二、
交互式 bash shell 获取进程 pid
在已知进程名(name)的前提下,交互式 shell 获取进程 pid 有很多种方法,典型的通过 grep 获取 pid 的方法为(这里添加-v grep是为了避免匹配到 grep 进程):
ps -ef | grep "name" | grep -v grep | awk '{print $2}'
或者不使用 grep(这里名称首字母加[]的目的是为了避免匹配到 awk 自身的进程):
ps -ef | awk '/[n]ame/{print $2}'
如果只使用 x 参数的话则 pid 应该位于第一位:
ps x | awk '/[n]ame/{print $1}'
最简单的方法是使用 pgrep:
pgrep -f name
如果需要查找到 pid 之后 kill 掉该进程,还可以使用 pkill:
pkill -f name
如果是可执行程序的话,可以直接使用 pidof
pidof name
bash shell 脚本获取进程 pid
根据进程名获取进程 pid
在使用 shell 脚本获取进程 pid 时,如果直接使用上述命令,会出现多个 pid 结果,例如:
1 2 3 4 5 | ps x | grep | grep -v grep | awk |
执行 process-monitor.sh 会出现多个结果:
$> sh process-monitor.sh3036 3098 3099进一步排查可以发现,多出来的几个进程实际上是子 shell 的(临时)进程:
root 3036 2905 0 09:03 pts/1 00:00:45 /usr/java/jdk1.7.0_71/bin/java ...nameroot 4522 2905 0 16:12 pts/1 00:00:00 sh process-monitor.sh nameroot 4523 4522 0 16:12 pts/1 00:00:00 sh process-monitor.sh name其中 3036 是需要查找的进程pid,而 4522、4523 就是子 shell 的 pid。 为了避免这种情况,需要进一步明确查找条件,考虑到所要查找的是 java 程序,就可以通过 java 的关键字进行匹配:
1 2 3 4 5 | ps -ef | grep | grep | grep -v grep | awk |
获取 shell 脚本自身进程 pid
这里涉及两个指令: 1. $$ :当前 shell 进程的 pid 2. $! :上一个后台进程的 pid 可以使用这两个指令来获取相应的进程 pid。例如,如果需要获取某个正在执行的进程的 pid(并写入指定的文件):
mycommand && pid=$!mycommand & echo $! >/path/to/pid.file注意,在脚本中执行 $! 只会显示子 shell 的后台进程 pid,如果子 shell 先前没有启动后台进程,则没有输出。
查看指定进程是否存在
在获取到 pid 之后,还可以根据 pid 查看对应的进程是否存在(运行),这个方法也可以用于 kill 指定的进程。
if ps -p $pid > /dev/nullthenecho "$pid is running"# do something knowing the pid exists, i.e. the process with $pid is running fi
三、判断进程的状态
#pid=`ps -ef | grep java | grep flume | awk '{ print $2 }'`
#ps -ef |grep hello |awk '{print $2}'|xargs kill -9
#!/bin/bash
condir=/app/cfg/content-hist-b
startfile=/app/etc/init.d/content-hist-b
pid=content-hist-b
echo "d&gby1900d129" |sudo -s /usr/sbin/sysctl -w vm.drop_caches=3;
count=`pgrep -f $pid` && echo $count;
if [ -n "$count" ]; then
sleep 1;
echo "prcoess is busy";
kill -9 $count;
sleep 60;
cd $condir && sh clean.sh && $startfile restart;
else
echo "prcoess is stop";
cd $condir && sh clean.sh && $startfile restart;
fi
exit;
转载于:https://blog.51cto.com/evileve/1719197
总结
以上是尊龙游戏旗舰厅官网为你收集整理的获取进程号并赋值判断进程状态的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: php编程中的并发
- 下一篇: