stdio buffering vs raw system calls
Choose between stdio and raw syscalls and control buffering and flushing.
By Invicly Tech, , in Linux System Programming. About 12 minutes to read.
In short
stdio functions like printf and fgets keep a user-space buffer and only call write or read when it fills or is flushed. This cuts the number of expensive system calls dramatically. The trade-off is that buffered data can appear late, out of order with raw writes, or be lost if the process crashes or calls _exit.
Explained simply
Every system call costs much more than an ordinary function call, because the CPU has to switch into the kernel and back. If a program wrote a 1 MB file one byte at a time with write, it would make a million of these trips.
The C library's stdio functions (printf, fputs, fgets, fwrite) solve this with a buffer, a block of memory inside your own process. Small writes are collected there and handed to the kernel in one big write, usually 4096 bytes at a time. Reading works the same way in reverse.
A FILE pointer, such as stdout or what fopen returns, is a small structure that holds a descriptor plus this buffer. fileno(fp) gives you the descriptor inside it.
The buffer brings surprises. Output can appear late. Text from printf and from raw write can come out in the wrong order. Output can be printed twice after fork, or lost if the program crashes. Once you know when the buffer is flushed, all of these make sense.
Press Play on a diagram to walk through it one step at a time.
- Program to stdio buffer: printf(...) called 1000 times1printf(...) called 1000 times
- stdio buffer to Kernel: write(1, buf, 4096) only when the buffer fills2write(1, buf, 4096) only when the buffer fills
- Program to stdio buffer: fflush(stdout) or exit()3fflush(stdout) or exit()
- stdio buffer to Kernel: write(1, buf, remaining bytes)4write(1, buf, remaining bytes)
- Flushes when the buffer is full
- Default for files and pipes
- Fewest system calls
- Output can appear much later
- Flushes at each newline
- Default for stdout on a terminal
- Good for interactive programs
- One write call per line
- Every call goes straight to write
- Default for stderr
- Output appears immediately
- Slowest for many small writes
In depth
Where your bytes wait: two different buffers
Output passes through two separate buffers before it reaches a disk. The first is the stdio buffer in your process. fflush empties it into the kernel with a write call. If your process crashes before that, the bytes are simply gone.
The second is the kernel's page cache. After write returns, other processes can already read the data, but it may not be on the disk yet. fsync empties that buffer for one file.
Keeping the two apart clears up a lot of confusion. fflush makes data visible to other programs. fsync makes it survive a power cut. A log that must survive a crash of your program needs fflush. A database commit that must survive a power cut needs fsync too.
- 1Your code
printf, fputs, fwrite
- 2stdio buffer (your process)
Lost if the process crashes; fflush empties it
- 3write() system call
Data enters the kernel
- 4Page cache or pipe buffer (kernel)
Visible to readers now; fsync empties it to disk
- 5Disk or the reading process
The final destination
How glibc picks the buffering mode
When a stream is first used, glibc checks what is behind it. stdout connected to a terminal is line buffered: it flushes at every newline. stdout connected to a file or pipe is fully buffered: it flushes only when the buffer fills. stderr is always unbuffered, so error messages appear at once. glibc sizes the buffer from the file's block size, which is usually 4096 bytes.
glibc also flushes line-buffered output when it must read from the terminal, which is why printf("Name: ") without a newline usually shows up before fgets waits. Do not rely on it: call fflush(stdout) after a prompt.
To choose a mode yourself, call setvbuf(stream, buf, mode, size) with _IOFBF, _IOLBF or _IONBF. It must come before any other operation on that stream. If you pass your own buffer, it must stay valid until the stream is closed, so never pass a local array from a function that returns.
- Terminal stdout: line buffered
- File or pipe stdout: fully buffered
- stderr: unbuffered
- setvbuf: first call on the stream, or it may be ignored
Counting system calls with strace -c
strace -c runs a program and prints a table of how many times each system call was made and how long they took. It is the quickest way to see what buffering does for you.
Write one million single characters with write(1, "x", 1) and strace -c reports about one million write calls. Write them with putchar into a pipe or file and it reports about 245, because each call moves a full 4096-byte buffer. The run time drops by a large factor too.
The same trick finds performance bugs in real programs. If a tool makes tens of thousands of tiny reads or writes, it is probably using raw calls on small pieces, or calling fflush far too often. Add -e trace=write to focus on one call, and -f to include child processes.
fork, exit, _exit and lost output
The stdio buffer is ordinary memory, so fork copies it. If unflushed text is waiting when you fork, both parent and child own a copy, and both print it when they exit. With a terminal this often goes unnoticed because the newline already flushed the line. With a pipe, every line printed before the fork appears twice. The fix is fflush(NULL) right before fork, which flushes every output stream.
exit and returning from main flush all streams. _exit does not; it goes straight to the kernel. That is exactly why a child that fails to exec must call _exit: it must not flush a copy of the parent's buffer. A crash from a signal such as SIGSEGV also skips the flush, so the last printf lines before a crash are often missing. When debugging a crash, print to stderr, which is unbuffered.
When to use stdio and when to use raw calls
Use stdio for text: formatted output, reading line by line with fgets or getline, and many small reads or writes. It is portable, convenient and fast.
Use raw descriptors when you need exact control. That means sockets and pipes watched with poll or epoll, where hidden buffered data would confuse the event loop. It also means large binary blocks, which already make one call each, and cases where you need to know exactly when a write reaches the kernel.
Do not mix stdio and raw write on the same descriptor. If you must, call fflush on the stream before each raw write, or the output will be out of order. For reading this is worse: once stdio has read ahead into its buffer, a raw read on the same descriptor skips the bytes that stdio is holding.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Compare FILE streams with descriptors~45m
- 2Explain full, line and unbuffered modes~45m
- 3Control buffering with setvbuf and fflush~45m
- 4Measure syscall counts with strace -c~45m
Key points
- stdout is line buffered on a terminal and fully buffered when redirected to a file or pipe.
- stderr is unbuffered so error messages appear immediately.
- fflush forces buffered data out; exit flushes but _exit does not.
- Do not mix stdio and raw write on the same descriptor without flushing.
Key terms
Tap a card to flip it. 0/6 known
Examples
#include <stdio.h>
#include <unistd.h>
int main(void) {
printf("hello "); // waits in the stdio buffer
write(1, "world\n", 6); // goes straight to the kernel
fflush(stdout);
return 0;
}
// ./a.out | cat prints: world, then helloRun it with and without a pipe to see buffering change the order.
Progress messages that vanish in a pipe
A worker prints one progress line per second. Run directly in a terminal, the lines appear one by one. Run as ./worker | tee run.log, nothing shows for a long time, then everything appears at once. Step 1: understand why: stdout is now a pipe, so it is fully buffered and waits for 4096 bytes. Step 2: fix it in code by switching stdout to line buffering at the very start. Step 3: if you cannot change the code, run stdbuf -oL ./worker | tee run.log, which works for programs that use glibc stdio and do not set their own buffering.
#include <stdio.h>
#include <unistd.h>
int main(void) {
/* Must come before any other output on stdout. */
if (setvbuf(stdout, NULL, _IOLBF, 0) != 0)
fprintf(stderr, "setvbuf failed\n");
for (int i = 1; i <= 5; i++) {
printf("step %d of 5\n", i);
sleep(1);
}
return 0;
}Measure what buffering saves
Build two programs that each write one million x characters. Step 1: slow.c calls write once per character. Step 2: fast.c uses putchar, so stdio batches the characters. Step 3: count write calls with strace -c: about 1,000,000 for slow and about 245 for fast (1,000,000 divided by 4096, plus the final partial flush). Step 4: time both; the buffered one is usually dozens of times faster.
cat > slow.c <<'EOF'
#include <unistd.h>
int main(void) { for (int i = 0; i < 1000000; i++) if (write(1, "x", 1) != 1) return 1; return 0; }
EOF
cat > fast.c <<'EOF'
#include <stdio.h>
int main(void) { for (int i = 0; i < 1000000; i++) putchar('x'); return 0; }
EOF
gcc -O2 -o slow slow.c && gcc -O2 -o fast fast.c
strace -c -e trace=write ./slow > /dev/null
strace -c -e trace=write ./fast > /dev/null
time ./slow > /dev/null; time ./fast > /dev/nullQuick reference
- stdout is line buffered on a terminal and fully buffered into a file or pipe; stderr is unbuffered
- setvbuf(stdout, NULL, _IOLBF, 0) as the first call makes stdout line buffered everywhere
- Call fflush(stdout) after a prompt that has no newline
- fflush(NULL) flushes every output stream; do it right before fork()
- fileno(fp) gives the descriptor inside a FILE; fdopen(fd, "r") wraps a descriptor in a FILE
- stdbuf -oL cmd forces line-buffered stdout for most glibc programs
- strace -c -e trace=write ./prog counts the write calls a program makes
- exit() flushes stdio buffers; _exit() and crashes do not
Common mistakes
- Calling fork with unflushed stdout, so the child prints the buffered text again.
- Expecting printf output to appear before a crash.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Print the prompt "Enter your name: " without a newline, read a line with fgets, and greet the user. Make sure the prompt also appears when stdout is a pipe, as in ./a.out | cat.
- Exercise 2medium
Write a program that calls printf("before fork\n") and then fork(), with both processes exiting normally. Run it in a terminal and as ./a.out | cat, explain the difference, then fix it.
- Exercise 3hard
Write a tiny buffered writer: a struct holding a descriptor, a 4096-byte buffer and a length, plus bw_putc and bw_flush. Use it to write one million characters and confirm with strace -c that only about 245 write calls happen.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why does my printf output not show up?
- It is probably still in the stdio buffer, usually because stdout is a file or pipe and no newline or flush has happened. Call fflush(stdout), end lines with a newline on a terminal, or print diagnostics to stderr.
- Is printf thread-safe?
- Yes. POSIX requires stdio functions to lock the stream, so the output of one printf call is not mixed with another thread's call. Several separate calls from different threads can still interleave.
- Should I use fwrite or write for binary files?
- Either works. fwrite is better for many small pieces because it batches them. write is fine for large blocks and gives you exact control over when data reaches the kernel.
- What is BUFSIZ?
- A constant from stdio.h meant as a good buffer size; it is 8192 in glibc. glibc actually sizes each stream's buffer from the file's block size, which is usually 4096 bytes.