linux - 如果程序没有运行,通过检查他的 pid 重新启动它

标签 linux bash shell

你们谁能告诉我我的 bash 脚本是否不错。我的目标是这个脚本在 bash.pid(包含 pid 号的文件)中查找,然后如果 pid 正在运行,脚本将退出 0,如果没有,它会重新运行我正在执行的程序 ./run

脚本:

#!/bin/sh
# Printing the directory
pwd > dir.dir
dir=$(cat dir.dir)
# Identifying the directory
pid=\$(cat $dir/bash.pid
# looking if pid is running - if it is running just exit
if \$(kill -CHLD \$pid >/dev/null 2>&1)
then
exit 0
fi
fi
# if not running then re-launch the program
cd $dir
./run &>/dev/null" > upd
chmod u+x upd
./upd

谢谢。

最佳答案

我不知道应用程序“运行”或“udp”是否是您要运行的应用程序。假设它是“运行”。

在你的脚本结束时,应该将运行的pid写入bash.pid,以便脚本下次检查。

重启“运行”后,我们应该再次确认它是否启动。

通常我们使用run.pid来保存运​​行的pid。

#!/bin/sh
# Printing the directory
pwd > dir.dir
dir=$(cat dir.dir)
# Identifying the directory
pid=$(cat $dir/bash.pid)
# looking if pid is running - if it is running just exit
if $(kill -CHLD $pid >/dev/null 2>&1)
then
    echo  "run has been started\n"
    exit 0
fi
# if not running then re-launch the program
cd $dir
chmod u+x run
./run & 
pgrep run > bash.pid
pid=$(cat $dir/bash.pid)
if $(kill -CHLD $pid >/dev/null 2>&1)
    echo "failed to start run \n"
then
    echo  "run has been started\n"
fi

关于linux - 如果程序没有运行,通过检查他的 pid 重新启动它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46963151/

相关文章:

linux - 什么时候调用setsockopt?在 bind() 和 connect() 之前?

python - 如何使用pexpect自动输入ssh私钥密码

linux - 谁吃了我的内存?

linux - 如何从shell检测wget的下载速度为零

linux - 定义引用其他别名的别名

linux - shell 脚本 : ftp to check existing file

python - 在 Python 中传递的 Unix 套接字凭证

linux - 如何在我的应用程序的目录树中使源位置独立?

c - 使用 EOL 模拟 STDIN 输入

bash - 在 bash 脚本的循环中使用 nohup