Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.

C




#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 write.geeksforgeeks.org or mail your article to review-team@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.

My Personal Notes arrow_drop_up
Last Updated : 10 Oct, 2022
Like Article
Save Article
Similar Reads
Related Tutorials