Is a return value of 0 from write(2) in C an error?

前端 未结 4 1332
慢半拍i
慢半拍i 2020-12-15 08:07

In the man page for the system call write(2) -

ssize_t write(int fd, const void *buf, size_t count);

it says the following:

4条回答
  •  自闭症患者
    2020-12-15 08:29

    This will ensure that the code does not spin indefinitely, even if the file descriptor is not a TCP socket or unexpected non-blocking flags are in effect. On some systems, certain legacy non-blocking modes (e.g. O_NDELAY) cause write() to return 0 (without setting errno) if no data can be written without blocking, at least for certain types of file descriptors. (The POSIX standard O_NONBLOCK uses an error return for this case.) And some of the non-blocking modes on some systems apply to the underlying object (e.g. socket, fifo) rather than the file descriptor, and so could even have been enabled by another process having an open file descriptor for the same object. The code protects itself from spinning in such a situation by simply treating it as an error, since it is not intended for use with non-blocking modes.

提交回复
热议问题