Multiple fork calls cause BlockingIOError

余生颓废 提交于 2021-01-27 20:29:00

问题


I'm searching for an explanation about the error I get with the following snippet :

#!/usr/bin/env python3

import os, sys

if __name__ == '__main__':
    while True:
        pid = os.fork()
        if pid == 0:
            sys.exit()
        elif pid > 0:
            pass
            # os.waitpid(pid, 0)
        else:
            sys.exit()

This will spawn many processes (processes that exit as they are spawned).

This will eventually cause a BlockingIOError showing like this :

Traceback (most recent call last):
  File "./asd.py", line 7, in <module>
    pid = os.fork()
BlockingIOError: [Errno 35] Resource temporarily unavailable

But when the os.waitpid call is uncommented, everything seems to be fine.

Why does this error occurs and what does this waitpid call may change about it?


回答1:


It's the same problem whenever fork dies this way; the error message is just how EAGAIN is conveyed to you:

  1. You're out of memory or
  2. You've hit the process limit (e.g. RLIMIT_NPROC)

waitpid fixes it because it reaps the zombie child processes; until you do that, those processes count towards the cap (it has to preserve them so the parent can look at the termination information).

You can see the various fork error codes documented on its man page.



来源:https://stackoverflow.com/questions/44534288/multiple-fork-calls-cause-blockingioerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!