You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在两个运行中的后台shell脚本之间实现消息通知?

Shell 跨脚本通知实现方案

方案1:自定义信号通知(最推荐,轻量无IO开销)

原理:Linux/Unix 系统提供两个无系统预设行为的用户自定义信号SIGUSR1、SIGUSR2,可直接用于进程间的简单通知场景。

各脚本实现示例

  • 脚本3(通知接收方,后台运行)
#!/bin/bash
# 绑定SIGUSR1信号的触发逻辑
trap 'echo "Hello 3"; exit 0' SIGUSR1
# 常驻进程等待信号
while :
do
    sleep 1
done
  • 脚本2(状态检测+通知发送方,后台运行)
#!/bin/bash
# 循环检测脚本1的存活状态
while :
do
    # 假设脚本1的文件名为shell1.sh,不存在则进入触发逻辑
    if ! pgrep -f "shell1.sh" > /dev/null; then
        # 获取脚本3的进程ID
        shell3_pid=$(pgrep -f "shell3.sh")
        if [ -n "$shell3_pid" ]; then
            # 向脚本3发送自定义信号
            kill -SIGUSR1 $shell3_pid
        fi
        exit 0
    fi
    sleep 1
done
  • 脚本1(测试用,后台运行)
#!/bin/bash
echo "Hello 1"
# 模拟常驻进程等待被kill
while :
do
    sleep 1
done

测试操作步骤

  1. 给三个脚本赋予执行权限:chmod +x shell1.sh shell2.sh shell3.sh
  2. 依次后台启动三个脚本:./shell1.sh & ./shell2.sh & ./shell3.sh &
  3. 手动终止脚本1进程:pkill -f shell1.sh,终端会直接输出Hello 3

方案2:标记文件触发(兼容性更强,无信号丢失风险)

原理:通过文件系统的临时标记文件作为通知载体,适合跨用户、跨容器等无法直接发送进程信号的场景。

代码调整点

  • 脚本2检测到脚本1停止后,只需执行touch /tmp/trigger_hello3即可完成通知
  • 脚本3调整为轮询检测标记文件的逻辑:
#!/bin/bash
while :
do
    if [ -f "/tmp/trigger_hello3" ]; then
        echo "Hello 3"
        # 删除标记文件避免重复触发
        rm -f /tmp/trigger_hello3
        exit 0
    fi
    sleep 1
done

内容的提问来源于stack exchange,提问作者Science Rocker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:48:02