问题 从bash中读取管道时,“读取”没有超时


我使用创建管道

mkfifo /tmp/foo.pipe

现在,我想尝试从管道读取最多2秒,所以我执行

read -t 2 line < /tmp/foo.pipe

超时不会发生。读只是坐在那里等待管道的输入。

手册说'read'应该与命名管道一起使用。有谁知道为什么会这样?

ls -al /tmp/foo.pipe
prw-r----- 1 foo bar 0 Jun 22 19:06 /tmp/foo.pipe

12415
2018-06-23 02:14


起源

acceptAnswer |问问题 - Eric Fortis
欢迎来到Stack Overflow!如果您通过单击最佳答案旁边的绿色复选标记(如果有答案)接受了问题的答案,那么人们就更有可能回答您的问题。 - Adam Rosenfield


答案:


在调用read builtin之前,你的shell在open()调用时被阻塞。

在Linux上,您可以同时打开FIFO进行读写操作,以防止打开时阻塞;这是不可移植的,但可以做你想要的。

read -t 2 <>/tmp/foo.pipe

改编自: 带有非阻塞读取的Bash脚本


16
2018-06-23 02:35





如果您只想刷新(并丢弃)FIFO中的数据:

dd iflag=nonblock if=/tmp/foo.pipe of=/dev/null &> /dev/null

1
2017-11-08 19:35





你的shell是持有它的那个,它试图从管道中读取数据以将数据提供给read命令,并且由于它没有得到任何东西它只是坐在那里等待。


0
2018-06-23 02:26





TMOUT=2
read line < /tmp/foo.pipe

-1
2017-10-20 00:07



这只是设置默认超时,它不会改变方式 read 实际上实现了超时。 - Barmar