0
votes

According to the textbook I am reading, the code below creates N child processes that will exit with unique statuses.

/* Parent creates N children */
for (i = 0; i < N; i++)
    if ((pid[i] = Fork()) == 0) /* Child */
        exit(100+i);

Earlier in the textbook, it states that the following code will have 8 lines of output:

int main(){
    Fork();
    Fork();
    Fork();
    printf("hello\n");
    exit(0);
}

This leads me to believe that there are 2^n child processes, where n is the number of times fork() is called. Is the reason the first code only produces N child processes (as opposed to 2^N) because the child exits every time, so by the time the subsequent fork() is called, it only operates on the parent process?

2
in the second case all the children continue on forking and printing. In the first case the child exits as soon as it is created so only the parent continuesJerry Jeremiah
@JerryJeremiah Thank you! This answers my question!user2821275
You should probably mention which book you're using. I know Stevens "UNIX Network Programming" uses the initial-capital system call names to specify the error-checked versions of system calls.Jonathan Leffler
@JonathanLeffler Sorry for the confusion, I am using CS: A Programmer's Perspective, and the capitalized version of fork() is intended to mean the error-checked version as well.user2821275
refer this link..Answer for your question is there.Ajith Ramsaran

2 Answers

1
votes

Every successful call to fork(), creates a new process.

In the first example, the children processes (the return value of fork() being 0) call exit();, which means they won't call the next fork().

In the second example, every children process continues forking.

1
votes

When fork() is called it copies the parent data and starts executing from that point individually. So the execution of the parent or child is depend on the scheduling of process. Whichever process get cpu time will be executed whether it is child or parent. We have to take care that which code should run by which process(child or process).