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:
The parent can use the system call wait() or waitpid() along with the macros WIFEXITED and WEXITSTATUS with it to learn about the status of its stopped child. (*)wait() system call : It suspends execution of the calling process until one of its children terminates. Syntax of wait() system call: pid_t wait(int *status);
fork() when called from a program it creates a new process. Thus executing os. fork() creates two processes: A parent process and a child process. The newly created child process is the exact replica of the parent process.
fork() method in Python is used to create a child process. This method work by calling the underlying OS function fork(). This method returns 0 in the child process and child's process id in the parent process.
fork() in C. Fork system call is used for creating a new process, which is called child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With