当父进程死亡时如何在子进程中检测?
在 python 中,我有一个父进程,它会生成一些子进程。我遇到过一种情况,由于未处理的异常,父进程正在死亡,子进程处于孤立状态。如何让子进程认识到它们已经失去了父进程?
我尝试了一些代码,将子进程与每个可用信号挂钩,但没有一个被触发。理论上,我可以在父进程周围放置一个巨大的 try/ except 来确保它至少向子进程触发一个 sigterm,但这是不优雅的而且不是万无一失的。如何防止孤立进程?
In python, I have a parent process that spawns a handful of child processes. I've run into a situation where, due to an unhandled exception, the parent process was dieing and the child processes where left orphaned. How do I get the child processes to recognize that they've lost their parent?
I tried some code that hooks the child process up to every available signal and none of them were fired. I could theoretically put a giant try/except around the parent process to ensure that it at least fires a sigterm to the children, but this is inelegant and not foolproof. How can I prevent orphaned processes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 UNIX(包括 Linux)上:
请注意,在 UNIX 上,信号 0 不是真正的信号。它仅用于测试给定进程是否存在。请参阅手册了解kill 命令。
on UNIX (including Linux):
Note, that on UNIX, signal 0 is not a real signal. It is used just to test if given process exists. See manual for kill command.
在创建子进程之前,您可以使用
socketpair()
创建一对unix域套接字。让父母一端打开,孩子另一端打开。当父进程退出时,它一端的套接字将关闭。然后子进程就会知道它已退出,因为它可以select()
/poll()
从其套接字读取事件并在此时接收文件结尾。You can use
socketpair()
to create a pair of unix domain sockets before creating the subprocess. Have the parent have one end open, and the child the other end open. When the parent exits, it's end of the socket will shut down. Then the child will know it exited because it canselect()
/poll()
for read events from its socket and receive end of file at that time.