Search code examples
clinuxglibcsystem-calls

Linux C Standard I/O - why double copying


Assuming I understand the flow correctly, one would like to read few byes off an opened FILE stream, lets says, using fread:

  1. the read syscall will copy the data from the kernel to the user space buffer
  2. user space buffer (either allocated by glibc or provided by setvbuf...) will be copied to the buffer provided to fread

why is the 2nd step needed? why can I get a pointer to the user space buffer which I will decide if I want to store (copy) or not?

Thanks,


Solution

  • The purpose of the 2nd buffer is to amortize the system call overhead. If you read/write only a few bytes at a time, this second user space buffer will improve performance enormously. OTOH if you read/write a large chunk, the 2nd buffer can be bypassed, so you don't pay the price for double copying.