fork() is a system call function which can generate child process from parent main process. Using some conditions we can generate as many child process as needed. We have given n , we have to create n-child processes from same parent process (main process ). Examples:
Input :3
Output :[son] pid 25332 from [parent] pid 25329
[son] pid 25331 from [parent] pid 25329
[son] pid 25330 from [parent] pid 25329
here 25332,25331,25330 are child processes from same parent process
with process id 25329
Input :5
Output :[son] pid 28519 from [parent] pid 28518
[son] pid 28523 from [parent] pid 28518
[son] pid 28520 from [parent] pid 28518
[son] pid 28521 from [parent] pid 28518
[son] pid 28522 from [parent] pid 28518
here 28519,28520,28521,28522,28523 are child processes from same parent process
with process id 28518.
#include<stdio.h>
int main()
{
for(int i=0;i<5;i++) // loop will run n times (n=5)
{
if(fork() == 0)
{
printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid());
exit(0);
}
}
for(int i=0;i<5;i++) // loop will run n times (n=5)
wait(NULL);
}
Output:
[son] pid 28519 from [parent] pid 28518 [son] pid 28523 from [parent] pid 28518 [son] pid 28520 from [parent] pid 28518 [son] pid 28521 from [parent] pid 28518 [son] pid 28522 from [parent] pid 28518