Reputation: 4922
i have a question about buffer in I/O programming in C.
For example, it is always said that fwrite is a buffered i/o, and write is an unbuffered i/o. My understanding is that the 'buffered' here is in application layer, and i think in kernel level, they both have a buffer. From APUE, i saw:
Traditional implementations of the UNIX System havea buffer cache or page cache in the kernel throughwhich most disk I/O passes. When we write data to a file,the data is normally copied by the kernel into oneof its buffers and queued for writing to disk at some later time. This is called delayed write.
Am i right? So i do a experiment:
int main() {
char *fname = "helloworld";
char content[] = "abcdefg";
int fd = open(fname, O_WRONLY | O_CREAT);
int flag = fcntl(fd, F_GETFL);
flag &= ~O_SYNC;
fcntl(fd, F_SETFL, flag);
write(fd, content, 3);
sleep(100);
return 0;
}
I thought there should be nothing outputed during sleep, but the fact is the opposite.
Is there something i misunderstood?
Upvotes: 1
Views: 2090
Reputation: 212238
There are multiple layers of buffering. If you call write
, no application layer buffering will occur. If you look at the file from another process you will see the data, but that does not mean they have been committed to disk, because there is a layer of buffering happening in the kernel. Since the kernel is handling the access from the other process, it is reporting the data in the buffer to that other process. In other words, from the perspective of all user-space applications the data has been written to the file, but it has not actually hit the disk.
Upvotes: 6