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

如何在Bash脚本中父进程挂起时同步挂起子进程?

问题

我有一个名为test.sh的Bash脚本,内容如下:

python test.py

如何修改该脚本,使其在自身收到SIGTSTP信号时,同步挂起Python子进程?


我的尝试

我直接向父进程发送SIGSTOP或SIGTSTP信号,但子进程仍会继续运行。

之后我尝试捕获信号并传递给子进程,但恢复时遇到了问题。我的代码如下:

#!/bin/bash

suspend_pid() {
    local pid=$1
    echo "Received SIGTSTP. Suspending child process $pid"
    kill -19 "$pid"
    echo "Suspending main process $$"
    kill -19 $$
}

continue_pid() {
    local pid=$1
    echo "Received SIGCONT. Resuming child process $pid"
    kill -18 "$pid"
    echo "Resuming main process $$"
    kill -18 $$
}

python test.py &
python_pid=$!

trap "suspend_pid $python_pid" SIGTSTP
trap "continue_pid $python_pid" SIGCONT

# Wait for the Python script to complete
wait $python_pid

echo "THE END"

这段代码能成功暂停父进程和子进程,但无法正常恢复。执行kill -SIGCONT <parent_pid>时,输出如下:

Received SIGCONT. Resuming child process 26944
Resuming main process 26942
Received SIGCONT. Resuming child process 26944
Resuming main process 26942
THE END
Received SIGCONT. Resuming child process 26944
Resuming main process 26942
Received SIGCONT. Resuming child process 26944
Resuming main process 26942

我猜测是continue_pid()函数中执行kill -18 $$时,再次触发了continue_pid()?


解决方案

你的猜测没错:捕获SIGCONT后又向自身发送该信号,会导致陷阱被无限触发,形成递归循环。

不需要单独捕获SIGCONT,只需优化SIGTSTP的处理逻辑即可,修改后的脚本如下:

#!/bin/bash

python test.py &
python_pid=$!

handle_tstp() {
    # 先暂停Python子进程
    kill -SIGTSTP "$python_pid"
    # 临时移除SIGTSTP陷阱,避免递归触发
    trap - SIGTSTP
    # 向自身发送SIGTSTP,让父进程进入暂停状态
    kill -SIGTSTP $$
    # 父进程被恢复后,重新设置SIGTSTP陷阱
    trap handle_tstp SIGTSTP
    # 恢复Python子进程
    kill -SIGCONT "$python_pid"
}

# 绑定SIGTSTP信号处理函数
trap handle_tstp SIGTSTP

# 等待子进程执行完成
wait $python_pid
echo "THE END"

逻辑说明

  1. 当父进程收到SIGTSTP时,先向子进程发送SIGTSTP将其暂停;
  2. 临时移除当前的SIGTSTP陷阱,避免后续向自身发送SIGTSTP时再次触发处理函数;
  3. 向自身发送SIGTSTP,让父进程进入系统默认的暂停状态;
  4. 当用户发送SIGCONT恢复父进程后,脚本会从kill -SIGTSTP $$的下一行继续执行:重新绑定SIGTSTP陷阱,再向子进程发送SIGCONT恢复其运行;
  5. 全程无需捕获SIGCONT,利用父进程恢复后的执行流程自动同步子进程的状态,彻底避免递归触发问题。

内容的提问来源于stack exchange,提问作者QZ Shao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:14:54