Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'read' not timing out when reading from pipe in bash

Tags:

bash

timeout

I create a pipe using

mkfifo /tmp/foo.pipe

Now, I want to try reading from the pipe for a maximum of 2 seconds, so I execute

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

The timeout does not occur. Read just sits there waiting for input from the pipe.

The manuals say that 'read' is supposed to work with named pipes. Does anyone have an idea why this is happening?

ls -al /tmp/foo.pipe
prw-r----- 1 foo bar 0 Jun 22 19:06 /tmp/foo.pipe
like image 237
i0exception Avatar asked Jun 23 '11 02:06

i0exception


2 Answers

Your shell is blocking on the open() call before invoking the read builtin.

On Linux, you can open the FIFO for both read and write at the same time to prevent blocking on open; this is non-portable, but may do what you want.

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

Adapted from: Bash script with non-blocking read

like image 124
MZS Avatar answered Nov 04 '22 00:11

MZS


If you just want to flush (and discard) the data from the FIFO:

dd iflag=nonblock if=/tmp/foo.pipe of=/dev/null &> /dev/null
like image 33
Ken A Avatar answered Nov 04 '22 00:11

Ken A