How to use a fork() system call
A fork() system call creates a new process which is called the child process. The process that creates the child process is the parent process.
To use the fork() system call, the program needs to include the unistd.h and sys/types.h header files:
#include <unistd.h>
#include <sys/types.h>
Explanation
After the creation of the child process, both the parent and the child process start execution from the next instruction after the fork() command. Both processes run concurrently.
When a child process is created, the contents of the memory of the parent process are copied to the memory allocated to the child process.
Parameters and return value
The fork() system call takes no argument and returns an integer value which can be any of the following:
-1: The value returned to the parent that indicates the creation of the child process was unsuccessful.0: The value returned to the child process.- Process id of the child process: The value returned to the parent that indicates the creation of the child process was successful.
Example
The following example demonstrates how to use the fork() system call in C.
- The below program creates a variable of type
pid_tfor storing the return value of thefork()system call. - The child and parent processes execute the appropriate conditional blocks depending on the value returned to them by the
fork()call. - The parent executes the
if elseblock and the child executes theifblock. - Both processes obtain their process ids through the
getpid()function and display them.
#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){pid_t pid;//create child processpid = fork();if (pid == 0){//inside child processprintf("I am the child process\n");pid_t pidchild;//get process idpidchild = getpid();printf("My id is %d\n", pidchild);}else if (pid > 0){//inside parent processprintf("I am the parent process\n");pid_t pidpar;pidpar = getpid();printf("My id is %d\n", pidpar);}return 0;}
Free Resources