CS FundamentalsVery hardGATE CS

stdout is a pipe (fully buffered) and every fork() succeeds. What is the complete output, up to the order of the lines?

stdout is a pipe (fully buffered) and every fork() succeeds. What is the complete output, up to the order of the lines?
int main() {
    printf("A");
    fork();
    printf("B\n");
}
  1. A. A once and B twice ("AB" and "B")
  2. B. A once and B once
  3. C. B twice only
  4. D. AB printed twice (two lines "AB")

Correct answer: D. AB printed twice (two lines "AB")

With full buffering, "A" is still in the stdio buffer at fork(), so the child inherits a copy. Each process then appends "B\n" and flushes at exit: "AB" appears twice. On a line-buffered terminal "A" would still be buffered too (no newline), so the same happens there.

More Operating Systems questions

Exams that ask this topic