Creating multiple process using fork() in C


In this section we will see how to use the fork() to make child process in C. We also do some different tasks in each process. So in our parent process we will print different values.

When fork() is called, it returns a value. If the value is greater than 0, then currently it is in parent process, otherwise it is in child process. So using this we can distinguish between the processes.

Example Code

#include <stdio.h>
#include <unistd.h>
int main() {
   int n = fork(); //subdivide process
   if (n > 0) { //when n is not 0, then it is parent process
      printf("Parent process 
";    } else { //when n is 0, then it is child process       printf("Child process
");    }    return 0; }

Output

soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Parent process
soumyadeep@soumyadeep-VirtualBox:~$ Child process
soumyadeep@soumyadeep-VirtualBox:~$

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements