linux 当bash脚本中的父进程被挂起时,挂起子进程的最佳方法是什么?

ruarlubt  于 2023-06-05  发布在  Linux
关注(0)|答案(1)|浏览(502)

提问

假设我有一个bash脚本test.sh,内容如下:

python test.py

如何修改bash脚本,使其在收到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()?

mitkmikd

mitkmikd1#

与Stack Overflow中的this answer类似,可以如下捕获python进程:

#!/bin/bash

# Set a trap for SIGTSTP
trap 'suspend_python' SIGTSTP

# Function to suspend the python process
suspend_python() {
  echo "Suspending Python process..."
  kill -TSTP $!
}

# Run the python process
python test.py

相关问题