如何使用 Python3 中的 multiprocessing.Process 使终止的进程递归终止其所有子进程?

如何使用 Python3 中的 multiprocessing.Process 使终止的进程递归终止其所有子进程?

我想在子进程内生成子进程,并使得如果父进程终止,则其每个子进程都会递归终止。

我目前使用 Python 作为编程语言,但我正在寻找一种与编程语言无关的解决方案。

令我困惑的是,每个都Process被配置为“守护进程”或“非守护进程”,具体取决于daemon的参数__init__(),该参数控制当父进程退出时子进程是否终止。

但是,正如以下文档所示,如果 aProcess是“守护进程”,那么它无法创建子进程,因此不可能实现我想要的,即当父进程退出时递归地终止子进程?

https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process.daemon:

daemon
The process’s daemon flag, a Boolean value. This must be set before start() is called.

The initial value is inherited from the creating process.

When a process exits, it attempts to terminate all of its daemonic child processes.

Note that a daemonic process is not allowed to create child processes. Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits. Additionally, these are not Unix daemons or services, they are normal processes that will be terminated (and not joined) if non-daemonic processes have exited.

相关内容