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>
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.
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.The following example demonstrates how to use the fork()
system call in C.
pid_t
for storing the return value of the fork()
system call.fork()
call.if else
block and the child executes the if
block.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