gpt4 book ai didi

linux - 如果父进程退出则暂停子进程退出

转载 作者:太空狗 更新时间:2023-10-29 12:24:42 26 4
gpt4 key购买 nike

我有以下进程树

test1.sh
\- test2.sh
\- sleep 600

通常,如果我终止 test1.sh 进程,子进程 test2.shsleep 600 将继续运行。但是如果我通过发送信号(SIGSTOP 或 SIGTSTP)暂停 sleep 600 进程,然后终止 test1.sh 进程,子进程 test2.shsleep 600 将退出。为什么?

这是我的测试程序:

test1.sh

#!/bin/sh

./test2.sh

test2.sh

#!/bin/sh

sleep 600

测试步骤:

  1. 运行 test1.sh

    $./test1.sh

  2. 打开新控制台并挂起子进程。

    $ kill -19 或 kill -20

  3. 杀死父进程test1.sh

    $ kill < test1.sh pid >

你会发现在step3之后,test2.sh和sleep 600退出了。

Bug如果我只运行step1和step3,忽略step2,test2.sh和sleep 600进程不会退出。

谁能解释一下?非常感谢。

最佳答案

当您终止进程 test1.sh 时,您会留下 test2.sh 孤儿,因此您需要了解操作系统中孤儿进程会发生什么情况。

当进程 test2.sh 正在运行并且其父进程死亡时,操作系统将其移至 init 进程并继续执行。所以结果是,即使您已终止 test1.shtest2.shsleep 进程仍在运行。

当进程 sleep 停止(信号 20)并且他的父进程死亡时,操作系统会尝试将其移动到 init 进程。然而,由于该进程已停止并且不再有任何 tty 能够恢复它(因为它的父进程已经死亡),操作系统可能决定对该进程做其他事情。在您的情况下,它会死于 SIGKILL 以避免系统周围出现许多停止的、孤立的进程的问题。由于sleep进程退出,test2.sh进程也结束。

来自 GNU 手册页:

While a process is stopped, no more signals can be delivered to it until it is continued, except SIGKILL signals and (obviously) SIGCONT signals. The signals are marked as pending, but not delivered until the process is continued. The SIGKILL signal always causes termination of the process and can’t be blocked, handled or ignored. You can ignore SIGCONT, but it always causes the process to be continued anyway if it is stopped. Sending a SIGCONT signal to a process causes any pending stop signals for that process to be discarded. Likewise, any pending SIGCONT signals for a process are discarded when it receives a stop signal.

When a process in an orphaned process group (see Orphaned Process Groups) receives a SIGTSTP, SIGTTIN, or SIGTTOU signal and does not handle it, the process does not stop. Stopping the process would probably not be very useful, since there is no shell program that will notice it stop and allow the user to continue it. What happens instead depends on the operating system you are using. Some systems may do nothing; others may deliver another signal instead, such as SIGKILL or SIGHUP. On GNU/Hurd systems, the process dies with SIGKILL; this avoids the problem of many stopped, orphaned processes lying around the system.

顺便说一下,如果你愿意一直杀死它们,你可以在主进程上添加一个trap来捕获信号并正确退出子进程。

关于linux - 如果父进程退出则暂停子进程退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45473414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com