Create n-child process from same parent process using fork() in C

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, 28519,28520,28521,28522 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

This article is contributed by Dibyendu Roy Chaudhuri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.