当父进程在 bash 脚本中暂停时,暂停子进程的最佳方法是什么?

问题描述 投票:0回答:2

问题

假设我有一个 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() ?

linux bash signals parent-child suspend
2个回答
0
投票

与 Stack Overflow 中的这个答案类似,您可以按如下方式捕获 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

0
投票

我通过挂起/继续子进程(使用

SIGUSR1
SIGUSR2
)并让父脚本等待子进程的终止来实现我想要的。

我将脚本更改为这样:

# Function to handle SIGTSTP signal
suspend_pid() {
    local pid=$1
    echo "Received SIGUSR1. Suspending child process $pid"
    kill -19 "$pid"
}

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

python -u test.py > test.py.out 2>&1 &
python_pid=$!

trap "suspend_pid $python_pid" SIGUSR1
trap "continue_pid $python_pid" SIGUSR2

while true; do
    process_status=$(ps -p $python_pid -o stat=)
    if [[ -n $process_status ]]; then
        sleep 1
    else
        break
    fi
done

echo "The End"

效果非常好。

© www.soinside.com 2019 - 2024. All rights reserved.