CS FundamentalsHardGATE CS · Amazon/Microsoft SDE MCQ
How many times is x printed? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)
How many times is x printed? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)
int main() {
if (fork() || fork())
fork();
printf("x");
}- A. 4
- B. 6
- C. 8
- D. 5
Correct answer: D. 5
In the parent the first fork() is nonzero, so || short-circuits and it forks once more (2 processes). The first child evaluates the second fork(): its parent side is nonzero and forks again (2), and the new child gets 0 and skips the body (1). Total 5.
More Operating Systems questions
- Which values are printed (in some order)? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice…
- 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…