user11417281
user11417281

Reputation:

Creating n child process in c using fork

I found this code in geeks4geeks and i can't seem to understand it properly:

#include<stdio.h> 


int main() 
{ 
    for(int i=0;i<5;i++) // loop will run n times (n=5) 
    {  pid_t c=fork();
        if(c == 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); 

} 

This code creates 5 processes from a father process and prints a message from each child.My question is this:Since we haven't used any restriction for c isn't for example the second fork executed by both father and first child process?Without isolating fork inside father's code how does this code not create 2^5 child processes?Is the for loop somehow stopping this from happening?

Upvotes: 3

Views: 12492

Answers (3)

mostafiz67
mostafiz67

Reputation: 169

In this program, they use exit(0), so the child process is exiting after it creation.

Upvotes: 0

dbush
dbush

Reputation: 225437

The child processes don't call fork because they exit before that happens:

for(int i=0;i<5;i++)
{   
    pid_t c=fork();
    if(c == 0)  // fork returns 0 to the child process so it enters "if" block
    { 
        printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid()); 
        // child exits
        exit(0); 
    } 
} 

If the if block did not contain exit then yes each child would iterate back to the top of the loop and potentially fork again. But since each child exits right after printing only the initial parent process calls fork, so you only create 5 processes.

Upvotes: 7

Pierce Griffiths
Pierce Griffiths

Reputation: 753

fork() returns 0 in the child process, while in the parent process it returns the PID of the child. Since the c has a value of 0 in the child, if(c == 0) will evaluate to true, the child will execute the printf statement, and then exit. It will never reach the loop evaluation statement.

Upvotes: 2

Related Questions