关于命名管道是否需要执行刷新操作的技术问询
fflush()? Great question—this is a super common point of confusion because FIFOs blur the line between pipes and regular files. Let’s break this down clearly:
First, core behavior of FIFOs
Even though FIFOs show up as regular-looking files in the filesystem, they’re kernel-managed pipes under the hood, not disk-backed files. The man page is right to call them similar to anonymous pipes—their data never hits the disk; it’s passed directly between processes via kernel buffers.
Buffering types to distinguish
The confusion usually stems from mixing up two totally separate buffering layers:
- Kernel-level pipe buffering: This is built into the FIFO/pipe mechanism. The kernel handles this automatically—you never need to "flush" it manually. Data stays here until a reading process picks it up, or the buffer fills up (at which point writes block until space frees up).
- User-space stdio buffering: This is the buffer managed by the C standard library (functions like
fprintf(),fputs(),fread()). By default, stdio uses full buffering for files (including FIFOs opened withfopen()), meaning it stores data in a user-space buffer until it’s full, or you explicitly flush it.
So do you need fflush() for FIFOs?
It depends entirely on how you’re writing to the FIFO:
- If using standard IO functions (stdio): Yes, you absolutely need
fflush(). For example, if you open a FIFO withfopen("myfifo", "w")and usefprintf()to write data, that data will sit in the stdio buffer until the buffer fills up, you callfflush(), or you close the file pointer. Until then, the reading process won’t see any data at all. - If using raw system calls (
write(),open()): No,fflush()doesn’t apply here. System calls write directly to the kernel’s pipe buffer, so the reading process can access the data immediately (assuming the kernel buffer has space).
Quick example to drive this home
Here’s a writing process using stdio without fflush()—the reader gets nothing until we explicitly flush:
FILE *f = fopen("myfifo", "w"); fprintf(f, "Hello from FIFO!\n"); // Reading process sees zilch right now fflush(f); // Now data hits the kernel buffer, reader gets it fclose(f);
Compare that to using system calls—data goes straight to the kernel:
int fd = open("myfifo", O_WRONLY); write(fd, "Hello from FIFO!\n", 17); // Reading process can grab this data immediately close(fd);
Key takeaway
FIFOs don’t require flushing the kernel buffer (that’s handled automatically), but if you’re using the C standard library’s IO functions, you need fflush() to push data out of the user-space buffer into the kernel pipe.
内容的提问来源于stack exchange,提问作者rph

