Introduction to the fork() system call
What you'll learn: How to create a brand-new process by duplicating the one currently running.
In systems programming, you often need a program to do two things at once. While threads are one way to achieve this, the classic Unix approach is to create an entirely new process using the fork() system call.
The Magic of Cellular Division
Think of fork() like biological cell division (mitosis). When a cell divides, it doesn't start from scratch; it makes a perfect copy of its DNA, organelles, and state, and then splits into two independent living things.
In C, when you call fork(), the operating system creates a "child" process that is a near-identical clone of the "parent" process. They share the same code, the same variables, and even the same instruction pointer—meaning the child starts executing at the exact same line where the fork() was called.
One Function, Two Returns
The most mind-bending part of fork() is that it is called once, but it returns twice: once in the parent and once in the child. To tell them apart, we check the return value:
- In the Parent:
fork()returns the Process ID (PID) of the new child. - In the Child:
fork()returns0.
Here is how you handle this "split" in your code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid;
printf("About to split...\n");
// The split happens here
pid = fork();
if (pid < 0) {
// Something went wrong (e.g., out of memory)
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
// This block only runs in the CHILD process
printf("I am the child! My PID is %d\n", getpid());
} else {
// This block only runs in the PARENT process
printf("I am the parent! I just created child %d\n", pid);
}
printf("Both processes run this line.\n");
return 0;
}
Independent Lives
Even though the child starts as a copy, it is now an independent entity. If the parent changes a variable after the fork, the child’s copy of that variable remains unchanged. They are like two identical twins who moved into separate houses; what happens in one house no longer affects the other.
Key takeaway
The fork() system call clones the current process, creating a parent-child relationship where both execute simultaneously from the point of the call.