vfork() – Why Use When Child Process Calls exec() or exit()

execexitlinuxprocessvfork

Operating System Concepts and APUE say

With vfork(), the parent process
is suspended, and the child process uses the address space of the parent.
Because vfork() does not use copy-on-write, if the child process changes
any pages of the parent’s address space, the altered pages will be visible to the
parent once it resumes. Therefore, vfork() must be used with caution to ensure
that the child process does not modify the address space of the parent.

vfork()
is intended to be used when the child process calls exec() or exit() immediately after
creation.

How shall I understand the last sentence?

When a child process created by vfork() calls exec(), doesn't exec() modify the address space of the parent process, by loading the new program?

When a child process created by vfork() calls exit(), does exit() not modify the address space of the parent process when terminating the child?

I have preference to Linux.

Thanks.

Best Answer

When a child process created by vfork() calls exec(), doesn't exec() modify the address space of the parent process, by loading the new program?

No, exec() provides a new address space for the new program; it doesn’t modify the parent address space. See for example the discussion of the exec functions in POSIX, and the Linux execve() manpage.

When a child process created by vfork() calls exit(), does exit() not modify the address space of the parent process when terminating the child?

Plain exit() might – it runs exit hooks installed by the running program (including its libraries). vfork() is more restrictive; thus, on Linux, it mandates the use of _exit() which doesn’t call the C library’s clean-up functions.

vfork() turned out to be quite difficult to get right; it’s been removed in current versions of the POSIX standard, and posix_spawn() should be used instead.

However, unless you really know what you’re doing, you should not use either vfork() or posix_spawn(); stick to good old fork() and exec().

The Linux manpage linked above provides more context:

However, in the bad old days a fork(2) would require making a complete copy of the caller's data space, often needlessly, since usually immediately afterward an exec(3) is done. Thus, for greater efficiency, BSD introduced the vfork() system call, which did not fully copy the address space of the parent process, but borrowed the parent's memory and thread of control until a call to execve(2) or an exit occurred. The parent process was suspended while the child was using its resources. The use of vfork() was tricky: for example, not modifying data in the parent process depended on knowing which variables were held in a register.