Which is the correct function to call to exit the child process after os.fork()?
The documentation for os._exit() states:
The standard way to exit is
sys.exit(n).
_exit()should normally only be used in the child process after afork().
It does not say whether it’s acceptable to terminate the child process using sys.exit(). So:
- Is it?
- Are there any potential side effects of doing so?
The unix way is that if you are a child of a
forkthen you call _exit. The main difference between exit and_exitis thatexittidies up more – calls theatexithandlers, flushesstdioetc, whereas_exitdoes the minimum amount of stuff in userspace, just getting the kernel to close all its files etc.This translates pretty directly into the python world with
sys.exitdoing whatexitdoes and doing more of the python interpreter shutdown, whereos._exitdoes the minimum possible.If you are a child of
forkand you callexitrather than_exitthen you may end up calling exit handlers that the parent will call again when it exits causing undefined behaviour.