问题
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:
- You're out of memory or
- 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