gpt4 book ai didi

bash - 如何检测我的 upstart 脚本是否正在运行?

转载 作者:行者123 更新时间:2023-12-04 18:26:49 25 4
gpt4 key购买 nike

在伪代码中,我试图做如下的事情

if myService is running
restart myService
else
start myService

如何将以上内容翻译成 bash 脚本或类似脚本?

最佳答案

标准方法是使用PID 文件来存储服务的PID。然后,您可以使用存储在 PID 文件中的 PID 来查看该服务是否已经在运行。

查看/etc/init.d目录下的各种脚本,看看它们是如何使用PID文件的。还要查看大多数 Linux 系统中的 /var/run 以查看 PID 文件的存储位置。

你可以做这样的事情,这是对所有 Bourne shell 类型的 shell 处理这个问题的通用方法:

# Does the PID file exist?

if [ -f "$PID_FILE" ]
then
# PID File does exist. Is that process still running?
if ps -p `cat $PID_FILE` > /dev/null 2&1
then

# Process is running. Do a restart
/etc/init.d/myService restart
cat $! > $PID_FILE
else
# Process isn't' running. Do a start
/etc/init.d/myService start
cat $! > $PID_FILE
else
# No PID file to begin with, do a restart
/etc/init.d/myService restart
cat $! > $PID_FILE
fi

但是,在 Linux 上,您可以利用 pgrep :

if pgrep myService > /dev/null 2>&1
then
restart service
else
start service
fi

请注意如何不使用任何大括号。 if 语句对 pgrep 命令的退出状态进行操作。我将 STDOUT 和 STDERR 都输出到/dev/null 因为我不想打印它们。我只想要 pgrep 命令本身的退出状态。

阅读 MANPAGE在 PGREP 上

有很多选择。例如,您可能希望使用 -x 来防止意外匹配,或者您可能必须使用 -f 来匹配用于启动服务的完整命令行。

关于bash - 如何检测我的 upstart 脚本是否正在运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10867488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com