FIFO 管道在 select() 中始终可读 [英] FIFO pipe is always readable in select()
问题描述
在 C 伪代码中:
while (1) {
fifo = open("fifo", O_RDONLY | O_NONBLOCK);
fd_set read;
FD_SET(fifo, &read);
select(nfds, &read, NULL, NULL, NULL);
}
进程在 select()
触发时休眠,直到另一个进程写入 fifo
.之后它总会找到 fifo
作为可读的文件描述符.
The process sleeps as triggered by select()
until another process writes into fifo
. Afterwards it will always find fifo
as a readable file descriptor.
如何避免这种行为(即在fifo
被读取一次后,如何让它在再次写入之前被发现为不可读?)
How to avoid this behavior (that is, after fifo
has been read once, how to make it be found as unreadable until it gets another write?)
推荐答案
你打开那个 FIFO 为只读(O_RDONLY),每当 FIFO 没有写入器时,读取端会收到一个 EOF
.
You opened that FIFO as read only (O_RDONLY), whenever there is no writer to the FIFO, the read end will receive an EOF
.
Select 系统调用将在 EOF
上返回,并且对于您处理的每个 EOF
,都会有一个新的 EOF
.这就是观察到的行为的原因.
Select system call will return on EOF
and for every EOF
you handle there will be a new EOF
. This is the reason for the observed behavior.
为了避免这种情况,为读取和写入 (O_RDWR) 打开 FIFO.这确保您在 FIFO 上至少有一个写入器,因此不会有 EOF
,因此除非有人写入该 FIFO,否则 select 不会返回.
To avoid this open that FIFO for both reading and writing (O_RDWR). This ensures that you have at least one writer on the FIFO thus there wont be an EOF
and as a result select won't return unless someone writes to that FIFO.
这篇关于FIFO 管道在 select() 中始终可读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!