5

openwrt 定时检查进程是否还在运行并自动重启(以 qbittorrent-nox 为例)

 2 years ago
source link: https://hellodk.cn/post/420
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

openwrt 定时检查进程是否还在运行并自动重启(以 qbittorrent-nox 为例)

众所周知 openwrt 的软件包不够完善,除了自己编译,目前官方或第三方源里都没有 systemd 这些程序

本文以 qbittorrent-nox 为栗子🌰

首先找到 qbittorrent-nox 的执行命令,是 /usr/bin/qbittorrent-nox --profile=/mnt/ThreeTB2/qbit_backup

编写 /mnt/ThreeTB2/check_qbittorrent.sh

#!/bin/bash
# author: hellodk
# time: 2021-01-10
# script feature description: check if qbittorrent-nox is running, if not, start it
function check_qbittorrent(){
qbittorrentCount=`ps aux | grep qbittorrent-nox |grep -v grep |wc -l`
echo "current running qbittorrent process count: "$qbittorrentCount
if [ 0 == $qbittorrentCount ]; then
nohup /usr/bin/qbittorrent-nox --profile=/mnt/ThreeTB2/qbit_backup >> /tmp/qbit.out.file 2>&1 &
check_qbittorrent
  • ps grep 的进程名称是 qbittorrent-nox 而不是 qbittorrent,楼主在这里踩过坑。而且 openwrt 中的 ps 没有相关参数,是个“简易版”的 ps 程序
  • 使用 |grep -v grep 过滤掉 grep 程序自身,避免统计错误
  • 使用 |wc -l 统计 匹配了 qbittorrent-nox 的程序数量
  • > 是重定向操作符 把前面的命令执行结果输出到文件 /tmp/qbit.out.file
  • 2>&1 把标准错误重定向到标准输出 &是等同于的意思
  • nohup command & 后台执行某个命令,即使终端进程关闭程序依然后台运行,即使用户退出进程也会继续运行

关于 linux 文件描述符
文件描述符.jpg

参考这篇文章: https://blog.csdn.net/cywosp/article/details/38965239

给这个 .sh 文件的所有用户添加可执行权限

chmod a+x /mnt/ThreeTB2/check_qbittorrent.sh

编写 cron 脚本 使用命令 crontab -e 进入类似 vi/vim 的编辑界面

0 0,6,12,18 * * * /bin/ash /mnt/ThreeTB2/check_qbittorrent.sh > /tmp/crontab-qbittorrent-sh.log

以上 cron 表达式代表 每天的 00:00:00、06:00:00、12:00:00和18:00:00 都会去执行这个 shell 脚本,并将脚本的标准输出内容 导出到 /tmp/crontab-qbittorrent-sh.log 文件中

然后重载 cron 服务并重启 即可

/etc/init.d/cron reload
/etc/init.d/cron restart

标签: Linux, openwrt

本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK