700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > linux shell if运行 bash – shell脚本执行检查是否已经在运行

linux shell if运行 bash – shell脚本执行检查是否已经在运行

时间:2018-07-24 02:33:22

相关推荐

linux shell if运行 bash – shell脚本执行检查是否已经在运行

检查已经执行的进程的更简单的方法是pidof命令.

if pidof -x "abc.sh" >/dev/null; then

echo "Process already running"

fi

或者,您的脚本在执行时创建一个PID文件.这是一个简单的练习,检查PID文件的存在以确定进程是否已经在运行.

#!/bin/bash

# abc.sh

mypidfile=/var/run/abc.sh.pid

# Could add check for existence of mypidfile here if interlock is

# needed in the shell script itself.

# Ensure PID file is removed on program exit.

trap "rm -f -- '$mypidfile'" EXIT

# Create a file with current PID to indicate that process is running.

echo $$> "$mypidfile"

...

更新:

现在,问题已经从脚本本身改变了.在这种情况下,我们希望总是看到至少有一个abc.sh运行.如果有多个abc.sh,那么我们知道进程仍在运行.我仍然建议使用pidof命令,如果进程已经运行,将返回2个PID.您可以使用grep过滤出当前的PID,在shell中循环,甚至还原到仅使用wc计数PID以检测多个进程.

以下是一个例子:

#!/bin/bash

for pid in $(pidof -x abc.sh); do

if [ $pid != $$]; then

echo "[$(date)] : abc.sh : Process is already running with PID $pid"

exit 1

fi

done

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。