Reputation: 500893
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:
Upvotes: 8
Views: 6492
Reputation: 18321
Part of the documentation on os._exit(n)
you did not cite is
Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.
So, how I'm reading this, you should use os._exit()
as long as you share file handlers (so they will be close()'d by another process and you take care of flushing the buffers yourself (if it matters in your case). Without shared resources (like in "files") - it doesn't matter.
So if your child processes are computation-only, and are fed raw data (not resource handlers), then it's safe to use exit()
.
Upvotes: 1
Reputation: 54117
The unix way is that if you are a child of a fork
then you call _exit. The main difference between exit and _exit
is that exit
tidies up more - calls the atexit
handlers, flushes stdio
etc, whereas _exit
does 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.exit
doing what exit
does and doing more of the python interpreter shutdown, where os._exit
does the minimum possible.
If you are a child of fork
and you call exit
rather than _exit
then you may end up calling exit handlers that the parent will call again when it exits causing undefined behaviour.
Upvotes: 9