vfork vs fork – Why Should a Child of a vfork or fork Call _exit() Instead of exit()?

cexitforksystem-calls

From the man page of vfork():

vfork() differs from fork() in that
the parent is suspended until the
child makes a call to execve(2) or
_exit(2). The child shares all memory with its parent, including the stack,
until execve() is issued by the child.
The child must not return from the
current function or call exit(), but
may call _exit().

Why should the child use an _exit() rather than simply calling exit()? I hope this is applicable to both vfork() and fork().

Best Answer

As seen earlier, vfork does not allow the child process to access the parent's memory. exit is a C library function (that's why it's often written as exit(3)). It performs various cleanup tasks such as flushing and closing C streams (the files open through functions declared in stdio.h) and executing user-specified functions registered with atexit. All these tasks involve reading and writing to the process memory.

_exit exits without cleanup. It's directly a system call (which is why it's written as _exit(2)), typically implemented by placing the system call number in a processor register and executing a particular processor instruction (branching to the system call handler). This doesn't need to access the process memory, so it's safe to do after vfork.

After fork, there is no such restriction: the parent and child process are now completely autonomous.