What is the difference between the fork() and vfork() system calls in Linux, and in what situations are they used?
sobes.tech AI
Answer from AI
fork() creates a new process (child) that is a copy of the parent process with a separate address space. After calling fork(), the parent and child operate independently, and changes in memory do not affect each other.
vfork() also creates a new process, but does not copy the parent's address space. Instead, the child uses the parent's memory until it calls exec() or _exit(). This speeds up process creation but imposes restrictions: the child should not modify memory or return from the function that called vfork(), otherwise behavior is undefined.
fork() is used when an independent process with a copy of memory is needed. vfork() is used for optimization when exec() is called immediately after process creation, and copying memory is unnecessary — this reduces overhead.
Example of using vfork():
pid_t pid = vfork();
if (pid == 0) {
// child immediately replaces the process image
execlp("ls", "ls", NULL);
_exit(1); // if exec fails
}
// parent continues to work