in Operating System recategorized by
10,803 views
3 votes
3 votes

The following $C$ program:

{
    fork(); fork(); printf("yes");
    
}

If we execute this core segment, how many times the string yes will be printed?

  1. Only once
  2. 2 times
  3. 4 times
  4. 8 times
in Operating System recategorized by
by
10.8k views

1 comment

Ans C)

#fork calls given in program = 2. Each fork call creates 2 processes (child + parent).

#child processes created here = $2^n-1$ = 3 // here n = 2; all of them prints "Yes"

#parent process = 1 //prints "Yes"

Thus total 4 prints.

3
3

3 Answers

9 votes
9 votes
Best answer
code can be re-written as

main {

fork();

fork();

printf("yes");

}

first fork() will going to create a child process,which is going to execute the next instruction i.e 2nd fork() and parent process also going to execute 2nd fork.

so now 2 more process will be created. so in system now there are 4 process and they are going to execute printf statement. so total no, of yes will be 4

++> Total number of times yes will be printed = 4
selected by
15 votes
15 votes

image

The FORK system call creates a child process & execution of FORK is in kernel mode. Its conversion takes place from user mode to system mode. A corresponding child process will be created in the program for every parent's process. so 4 times print statements are executed.

Ref: 1) GATE CSE 2012

       2) Understanding fork() system call

edited by

1 comment

This is a much better explanation.
1
1
7 votes
7 votes

OPTION C.

total no of child process is created=2^n-1 so"yes" is printed 3 times  and one "yes" is printed by parent .

1 comment

Nice explanation.
2
2
Answer:

Related questions