in Operating System
828 views
1 vote
1 vote

Consider the following C program:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (void)
{
    pid_t pid;
    int x = 2;
    pid = fork ( );
    if (pid = = 0);
         x = 8;
    fork( );
    printf("%d", x);
    return 0;
}

Fork ( ) is a system call creates new child process on successful execution. Assuming all invocations of fork are successful, which of the following is a correct output when the program is executed on the unix OS?[MSQ]

(a) 8 2 2 8       (b) 8 8 2 2       (c) 2 8 8 2      (d) 2 2 8 8

in Operating System
by
828 views

3 Comments

My thoughts -  as parent process doesn't wait for child after finishing it's own execution, (a) and (d) aren't possible
am I correct ?
0
0

Answer should be B and D

1
1
Thank you for solving but I still can’t understand why would 2 2 8 8 be possible because, if  parent is executing first, wouldn’t it be terminated once 2, 2 is printed? It doesn’t wait for a child by default right?
0
0

2 Answers

2 votes
2 votes
The order of execution between parent and child processes cannot be said.

Hence all the options are equally likely.

4 Comments

Thanks for answering but I can’t understand how can 8 be printed after both 2 are printed as parent doesn’t wait for a child by default
0
0
Parent is non blocking, but child also may not wait for parent. I think there is no implicit dependency with regards to the order of scheduling of parent and child processes, ther are all independent processes.
0
0
Can you please provide the final ans if you know. it should all or only B,D.
0
0
I think it should be all
0
0
0 votes
0 votes

if (pid = = 0); statement is of no use in parent and child processes because of semicolon.

None of the options are correct. correct ans is 8 8 8 8. because before print statement value of x is changed from 2 to 8 in parent and child both processes.

Related questions