Henry
Henry

Reputation: 587

why read -n from fifo file will lost data in shell

First I make a fifo

mkfifo a.fifo

Then I echo something to it

echo 1 > a.fifo

Open another terminal, and also add sth to it

echo 2 > a.fifo

Of course, the two are all blocked,then I read from the fifofile

read -n1 < a.fifo

All are released and I only got one and the other char is missing...

My question is why it happened and how can I get the content from fifo file one by one without losing data?

Thx

Upvotes: 0

Views: 855

Answers (1)

geirha
geirha

Reputation: 6181

By doing read -n1 < a.fifo, you

  1. Opened a.fifo for reading
  2. Read one character
  3. Closed a.fifo

Closing a fifo in either end, closes it in both ends.

Leave it open until you don't need it anymore.

exec 3< a.fifo    # open for reading, assign fd 3
read -r line1 <&3 # read one line from fd 3
read -r line2 <&3 # read one line from fd 3
exec 3<&-         # close fd 3

And at the other end:

exec 3> a.fifo       # open for writing, assign fd 3
printf 'hello\n' >&3 # write a line to fd 3
printf 'wolrd\n' >&3 # write a line to fd 3
exec 3>&-            # close fd 3

See http://wiki.bash-hackers.org/howto/redirection_tutorial for more on redirection

Upvotes: 4

Related Questions