Hard
Mutating a variable between vfork() and exec()
Unlike fork(), vfork() does not copy the parent's address space or use copy-on-write: the child runs using the parent's actual memory, and the parent is suspended until the child calls exec() or _exit(). Here, the child writes to a global variable before calling execl(). What does the parent print after it resumes?
main.cpp
#include <unistd.h>
#include <cstdio>
int global_counter = 100;
int main() {
pid_t pid = vfork();
if (pid == 0) {
global_counter = 999; // child mutates a variable before exec
execl("/bin/echo", "echo", "hi", nullptr);
_exit(1); // only reached if execl() fails
}
printf("parent: global_counter = %d\n", global_counter);
return 0;
}44 of 53 in Operating Systems