The fork() system call is a mechanism in Unix-based operating systems that allows a process to create a new child process. The new process is an exact copy of the parent process, including the program code, data, and stack. The only difference between the two processes is their process IDs (PIDs).
When a program calls fork(), the operating system creates a new process by duplicating the calling process. This new process is called the child process, and it runs the same code as the parent process. The child process has its own copy of the parent's address space, which means that any changes made to the memory by the child process will not affect the parent process.
The fork() system call returns different values to the parent and child processes. In the parent process, fork() returns the PID of the child process, while in the child process, it returns zero. This allows the parent and child processes to differentiate between each other and take different actions based on their respective PIDs.
After the child process is created, both the parent and child processes continue executing independently. The child process can use system calls like exec() to replace its program code with a new program, or it can use exit() to terminate itself. The parent process can use wait() or waitpid() system calls to wait for the child process to complete, or it can continue executing other code.
The fork() system call is commonly used in Unix-based operating systems to create new processes for multitasking and to implement parallel processing. By creating multiple processes that run concurrently, the system can utilize multiple CPUs and improve performance.
Sample code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid = getpid();
printf("Current process PID is %d\n", pid);
printf("Forking a child process...\n");
pid_t child_pid = fork();
if (child_pid == -1) {
printf("Failed to fork a child process.\n");
return 1;
}
else if (child_pid == 0) {
printf("Child process PID: %d, Parent process PID: %d\n", getpid(), getppid());
}
else {
printf("Parent process PID: %d\n", getpid());
}
return 0;
}