i0exception
i0exception

Reputation: 392

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

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

Upvotes: 12

Views: 5657

Answers (4)

Ken A
Ken A

Reputation: 401

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

Upvotes: 1

Marti
Marti

Reputation: 1

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

Upvotes: -1

MZS
MZS

Reputation: 583

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

Upvotes: 18

X-Istence
X-Istence

Reputation: 16667

Your shell is the one that is holding it up, it is attempting to read from the pipe to feed the data into the read command, and since it is not getting anything it just sits there waiting.

Upvotes: 0

Related Questions