ciosystem-callsread-write

Do read and write C system calls use buffers?


I was talking with a teacher and he told me that read and write system calls was using buffers, because there is a variable in your system spec that controls how many times you can have access to the device you want to read/write on, and the system uses buffer to stock data while he is waiting for writing on the device.

I saw on an other Stack Overflow post (C fopen vs open) that one of the advantages of fopen and fwrite functions was that those functions were using buffers (which is supposed to be way faster). I have read the man page of read and write sys calls, and the man pages do not talk about any buffers.

Did I misunderstood something ? How do read / write C syscall buffers work?


Solution

  • The functions you mention, read and write are system calls, therefore their behavior is platform dependent.

    As you know, fread and fwrite are C standard library functions. They do buffering in the user space and in this way optimize the performance for typical application. read and write are different. There is some stub code in userspace C libraries (such as GNU libc) for these functions, but the main function of that code is just to provide a convenient wrapper for invoking the right kernel functionality (but it's also possible to invoke that functionality with syscall() directly!)

    If you're interested in the details, here is an example: the wrapper for write system call in the uclibc library.

    So the typical implementations of read and write do not do buffering in user space. They may still do buffering in the kernel space, though. Read about the O_DIRECT flag for more details: How are the O_SYNC and O_DIRECT flags in open(2) different/alike?