Reputation: 587
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
Reputation: 6181
By doing read -n1 < a.fifo
, you
a.fifo
for readinga.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