Sub topic 5
Creating and Ending Processes with `fork`, `exec`, and `wait`
Prerequisites
Assume you know basic C, pointers, functions, and how a CPU runs instructions. You should also know that a process is a running program with its own address space and operating-system state.
Creating a Process with `fork`
The fork system call creates a new process called the child. The existing process becomes the parent. After fork returns, both processes continue from the next instruction.
The return value identifies the process:
-1means creation failed.0means the code is running in the child.- A positive value is the child’s process ID, returned to the parent.
The child initially has a copy of the parent’s memory and open file descriptors. Modern systems usually use copy-on-write: the pages are shared until one process modifies them. Changes made by one process do not normally change the other process’s variables.
Replacing a Process with `exec`
The exec family does not create another process. It replaces the current process image with a different program. The process keeps its process ID, but its code, data, stack, and registers are replaced.
If exec succeeds, it never returns. If it returns, an error occurred. A common pattern is to call exec in the child after fork.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
execlp("echo", "echo", "hello from the child", (char *)NULL);
perror("execlp");
_exit(127);
}
int status;
if (waitpid(pid, &status, 0) == -1) {
perror("waitpid");
return 1;
}
if (WIFEXITED(status)) {
printf("child exited with status %d\n", WEXITSTATUS(status));
}
return 0;
}The child runs echo. The parent calls waitpid, so it blocks until that particular child terminates. The parent can inspect the encoded status with macros such as WIFEXITED and WEXITSTATUS.
Use _exit in the child after a failed exec. It terminates immediately without flushing standard-I/O buffers inherited from the parent. Calling ordinary exit after fork can print buffered output twice.
Process Termination and Zombies
A process can terminate normally by returning from main or calling exit. It can also terminate because of a signal. The kernel keeps a terminated child’s exit status until its parent collects it with wait or waitpid. During this interval, the child is a zombie.
If the parent terminates first, the child is adopted by another system process. A parent that never waits may leave zombie entries in the process table.
Exercise
If a process calls fork once and both parent and child then call fork once more, how many processes exist?
Show answer
Four processes exist. The first fork creates two processes, and each of those performs the second fork, producing 2 × 2 = 4.