operating-system-fork.html
* created: 2025-05-18T00:00
* modified: 2025-06-03T08:58
title
Fork command
description
Executing the fork system call spawns a copy of the parent process. The resulting pid which gets returned indicates whether the process is the child or the parent.
related notes
Forking a process
The fork()
system call spawn a copy of the parent process. This newly created copy gets it's own id but keeps the same context as it's parent.
After forking the process both parent and child continue executing from the same point. The return value of fork()
returns the pid
of the child process, which implicitly indicates if the process is a child or a parent:
fork()
> 0 => The current process is the parent.
fork()
= 0 => The current process is the child.
fork()
< 0 => Something went horribly wrong, you should consider shutting down your computer and start living in the woods.
Example: In the following example you can see a simple C program which calls fork()
and prints if it's the child or the parent:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed!");
return 1;
} else if (pid == 0) {
printf("This is the child process. PID: %d, Parent PID: %d\n", getpid(), getppid());
} else {
printf("This is the parent process. PID: %d, Child PID: %d\n", getpid(), pid);
}
return 0;
}
This is what the output could look like:
This is the parent process. PID: 12597, Child PID: 12601
This is the child process. PID: 12601, Parent PID: 12597