edited by
1,257 views
0 votes
0 votes

Consider following pseudo code :
 

main()
{
    int t1,t2,t3;
    t1=t2=t3=0;
    t1=fork();
    t2=fork();
    if (t1!=0){
         t3=fork();
         printf("Hello");
     }
}


How many Hello's are printed when above code get executed.

  1. $1$
  2. $2$
  3. $3$
  4. $4$
edited by

2 Answers

Best answer
5 votes
5 votes

fork( ) returns zero to newly created child process, and a positive value to the parent process and a negative value if the child creation is unsuccessful. Assuming each call is successful, it will look like below.

 Let me name the different fork( ) calls as below:

    t1=fork(); //A
    t2=fork(); //B
    if (t1!=0)
    {  t3=fork(); //C
       printf("Hello");
    }

Notations: P for parent process, and C1,C2, C3,... for child processes.

After fork( ) - A, the value returned to parent is a positive value (i.e., the process ID of child process C1) and value returned to C1 is zero. Similarly, after fork( ) - B, child processes C2, C3 are created from parents P and C1 respectively.

The condition of if loop fails for  C1, C3. Only P and C2 executes the fork( ) - C and because of which child processes C4 and C5 are created. The printf statement is executed by P, C4, C2, C5 and four times Hello will be printed.

So option (D) should be correct. 

Please correct me, if I'm wrong.

selected by
1 votes
1 votes

System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork()system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork():

  • If fork() returns a negative value, the creation of a child process was unsuccessful.
  • fork() returns a zero to the newly created child process.
  • fork() returns a positive value, the process ID of the child process, to the parent. The returned process ID is of type pid_t defined in sys/types.h. Normally, the process ID is an integer. Moreover, a process can use function getpid() to retrieve the process ID assigned to this process.
  • REFERENCE -- http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html

From above points code works as follow.. at t1= fork() one instance (i.e child ) child will have value t1=0 where as parent instance will have any positive integer t1 = some +ive integer.

t2 = fork will also create two instance.

so on condition (t1 !=0) only parent instance at t1= fork() will pass (and it create two instance at t2=fork() i.e total two instance will pass the condition (t1 !=0)). t3=fork() will create two instance and both will print "Hello"

So, total 4 times "Hello " will be printed.