惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
U
Unit 42
IT之家
IT之家
Y
Y Combinator Blog
T
Tailwind CSS Blog
B
Blog
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
J
Java Code Geeks
F
Fortinet All Blogs
T
The Blog of Author Tim Ferriss
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
H
Hackread – Cybersecurity News, Data Breaches, AI and More
人人都是产品经理
人人都是产品经理
腾讯CDC
Hugging Face - Blog
Hugging Face - Blog
GbyAI
GbyAI
博客园 - 司徒正美
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
L
LangChain Blog

Bash

有个脚本代码的问题 Bash Script 代码比较,你认为哪个更加容易理解? 有使用 kitty 当日常终端的老哥吗? 在输入命令时,自动调用 fzf 进行模糊匹配 使用 shell 的 bash -c "functions"时,是不是所有相关的函数都得声明出来? shell 比较浮点数大小的问题,顺便吐槽以下 shell bash-completor:声明式编写 Bash 补全脚本 sudo 改用 pkexec 的问题 sed 如何查找替换反斜杠 lobash 发布 v0.5.0 版本 为什么这样写无法连接(join)数组各项? 如何使用 awk 打印 nginx 404 日志的目录 请教一下,怎么把向终端输入的内容重定向一份到文件? 请教一下 shell 里使用 jq 处理 json 应该怎么写 求一个 wsl2 ubuntu20.04 的默认 /etc/bash.bashrc 如何让 bash 的补全 popup 显示 如何去除 Bash variable expansion 后加的单引号? 初学者写了个 bash 脚本,求大佬点评 tar 使用管道的困惑 如何获取命令标准输出到变量里并保留颜色?或者能不能一边输出一边赋值或判断。 请问如何在 alias 命令里传递参数? Bash 下如何优雅地临时在后台运行程序并易于管理? shell tr -cd 匹配字符串问题 shell 中的 import 能不能支持 as 或 alias 类似功能 Shell 多个文本间隔追加的方法 生产服务器集群被黑了,帮看看这个脚本 如何实现一个符合规范的 shell? 请教下如何检测文件是否存在 bash 里面有 io 多路复用吗? 闲的蛋疼,用 shell 写了个拓扑排序。。。
Linux bash 脚本监控和重启一个守护进程
wisefree · 2024-04-28 · via Bash

最近有个需求,监控某个守护进程,如果进程不存在,则重启这个进程,打算写一个 bash 脚本和 service 服务满足这个需求。

  1. 通过 systemctl start monitor_process.service, 启动监控
  2. 通过 systemctl start monitor_process.service ,停止监控,同时杀死启动的进程。
  3. 这个服务必须是在系统所有服务启动之后,才启动该服务

看到 stackoverflow的高赞回答后,不知道这样写的脚本是不是合适的,有没有更加好实践。

我对 stackoverflow 高赞回答表示怀疑,其中jobs -p,无法列出后台的守护进程。因为一般编写守护进程代码时,都是 fork 两次并重新设置会话 setsid

trap 'kill $(jobs -p)' EXIT; until myserver & wait

monitor_process.sh


#!/bin/bash

this_bash_pid=$$
exe_name="thisIsExample"

# 定义一个函数来杀死进程
kill_process() {
  if [ -n "${PID}" ]; then
    kill -9 ${PID}
  fi
  exit
}

# 使用 trap 命令捕获 TERM, INT 和 EXIT 信号
trap 'kill_process' TERM INT EXIT

while true
do
  output=$(ps -ef | grep ${exe_name} | grep -v grep | grep -v ${this_bash_pid})

  if [ $? -eq 0 ];then
    PID=$(echo $output | awk '{print $2}')
    echo "${exe_name} :${PID} is running"
  else
    ./${exe_name} &

    output=$(ps -ef | grep ${exe_name} | grep -v grep | grep -v ${this_bash_pid})
    echo $output
    PID=$(echo $output | awk '{print $2}')
    echo $PID
  fi
  sleep 1
done

monitor_process.service


[Unit]
Description=Monitor Process Service
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/local/bin/monitor_process.sh
Restart=on-failure
RestartSec=30

[Install]
WantedBy=multi-user.target