Is O_NONBLOCK being set a property of the file descriptor or underlying file?

喜夏-厌秋 提交于 2019-12-02 19:12:13

O_NONBLOCK is a property of the open file description, not of the file descriptor, nor of the underlying file.

Yes, you could have separate file descriptors open for the same file, one of which is blocking and the other of which is non-blocking.

You need to distinguish between a FIFO (created using mkfifo()) and a pipe (created using pipe()).

Note that the blocking status is a property of the 'open file description', but in the simplest cases, there is a one-to-one mapping between file descriptors and open file descriptions. The open() function call creates a new open file description and a new file descriptor that refers to the open file description.

When you use dup(), you have two file descriptors sharing one open file description, and the properties belong to the open file description. The description of fcntl() says that F_SETFL affects the open file description associated with the file descriptor. Note that lseek() adjusts the file position of the open file description associated with the file descriptor - so it affects other file descriptors duplicated from the original one.

Removing the error handling from your code to reduce it, you have:

int fds[2];
pipe(fds);
int fd0_dup = dup(fds[0]);
fcntl(fd0_dup, F_SETFL, fcntl(fd0_dup, F_GETFL) | O_NONBLOCK);

Now both fd0_dup and fds[0] refer to the same open file description (because of the dup()), so the fcntl() operation affected both file descriptors.

if ((fcntl(fds[0], F_GETFL) & O_NONBLOCK)) { ... }

Hence the observed behaviour here is required by POSIX.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!