Why the fwrite libc function is faster than the syscall write function?

后端 未结 3 1773
Happy的楠姐
Happy的楠姐 2021-02-05 05:08

After providing the same program which reads a random generated input file and echoes the same string it read to an output. The only difference is that on one side I\'m providin

3条回答
  •  梦如初夏
    2021-02-05 05:23

    write(2) is the fundamental kernel operation.

    fwrite(3) is a library function that adds buffering on top of write(2).

    For small (e.g., line-at-a-time) byte counts, fwrite(3) is faster, because of the overhead for just doing a kernel call.

    For large (block I/O) byte counts, write(2) is faster, because it doesn't bother with buffering and you have to call the kernel in both cases.

    If you look at the source to cp(1), you won't see any buffering.

    Finally, there is one last consideration: ISO C vs Posix. The buffered library functions like fwrite are specified in ISO C whereas kernel calls like write are Posix. While many systems claim Posix-compatibility, especially when trying to qualify for government contracts, in practice it's specific to Unix-like systems. So, the buffered ops are more portable. As a result, a Linux cp will certainly use write but a C program that has to work cross-platform may have to use fwrite.

提交回复
热议问题