printf

Key idea: printf is usually user-space buffered I/O (stdio), not a syscall per character.

  • printf writes into a FILE buffer* in user space.
  • The actual syscall is typically write(fd, ...) when the buffer flushes.
  • Flushing happens when:
    • buffer is full
    • you print a newline to a terminal (line-buffered stdout)
    • you call fflush(stdout)
    • program exits normally (flushes stdio)
    • you print to stderr (often unbuffered by default)

The fork interaction gotcha (very interview-y):

  • After fork, the child gets a copy of the parent’s user-space buffers.
  • If stdout had buffered data not yet flushed, both processes may flush it, causing duplicated output.
  • Fix: fflush(stdout) before fork(), or use write() (unbuffered syscall) when you need strict behavior.