CS FundamentalsModerateGATE CS · Amazon/Microsoft SDE MCQ
Which values are printed (in some order)? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)
Which values are printed (in some order)? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)
int main() {
int x = 1;
if (fork() == 0) {
x += 2;
if (fork()) x *= 3;
} else {
x += 5;
}
printf("%d ", x);
}- A. 6, 9 and 9
- B. 6, 9 and 3
- C. 6 and 9 only
- D. 3, 6 and 18
Correct answer: B. 6, 9 and 3
The parent prints 1 + 5 = 6. The child makes x = 3 and forks: its parent side multiplies to 9, while the grandchild (fork() returned 0) keeps 3. Each process has its own copy of x.
More Operating Systems questions
- How many numbers are printed in total, and what is their sum? (Every fork() succeeds, and each print is an unbuffered write, so nothing is…
- What is the sum of all values printed? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through…
- Semaphores s = 2 and t = 0. T1 runs twice: wait(s); print('a'); signal(t). T2 runs twice: wait(t); print('b'); signal(s). Which outputs…
- Semaphores x = y = z = 0. T1: print A; signal(x); wait(y); print D. T2: wait(x); print B; signal(y); signal(z). T3: wait(z); print C…
- Shared x = 1. Three threads run once each, with no locking: T1 does x = x + 2, T2 does x = x 3, T3 does x = x − 1. Each statement is a…
- Shared x = 1. Thread A executes x = x + 1 twice; thread B executes x = x 2 once; each statement is a separate load and store and there is…