问题描述
一个python脚本需要通过fork()产生多个子进程.所有这些子进程应同时运行,而父进程应等待所有进程完成.有能力为慢"的孩子设置一些超时时间会很好.收集所有孩子后,父进程继续处理脚本的其余部分.
A python script need to spawn multiple sub-processes via fork(). All of those child processes should run simultaneously and the parent process should be waiting for all of them to finish. Having an ability to set some timeout on a "slow" child would be nice.The parent process goes on processing the rest of the script after all kids are collected.
解决问题的最佳方法是什么?谢谢.
What is the best way to work it out? Thanks.
推荐答案
简单示例:
import os
chidren = []
for job in jobs:
child = os.fork()
if child:
children.append(child)
else:
pass # really should exec the job
for child in children:
os.waitpid(child, 0)
给慢孩子一个时间要花点时间.您可以使用wait
而不是waitpid
,然后从子级列表中删除返回的值,而不必依次等待每个值(如此处所示).如果使用SIGALRM
处理程序设置了alarm
,则可以在指定的延迟后终止等待.这是所有标准的UNIX内容,而不是特定于Python的...
Timing out a slow child is a little more work; you can use wait
instead of waitpid
, and cull the returned values from the list of children, instead of waiting on each one in turn (as here). If you set up an alarm
with a SIGALRM
handler, you can terminate the waiting after a specified delay. This is all standard UNIX stuff, not Python-specific...
这篇关于通过fork()运行多个子流程的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!