Write and read from a fifo from two different script

Ciccio picture Ciccio · Sep 17, 2014 · Viewed 18.1k times · Source

I have two bash script. One script write in a fifo. The second one read from the fifo, but AFTER the first one end to write.

But something does not work. I do not understand where the problem is. Here the code.

The first script is (the writer):

#!/bin/bash

fifo_name="myfifo";

# Se non esiste, crea la fifo;
[ -p $fifo_name ] || mkfifo $fifo_name;

exec 3<> $fifo_name;

echo "foo" > $fifo_name;
echo "bar" > $fifo_name;

The second script is (the reader):

#!/bin/bash

fifo_name="myfifo";

while true
do
    if read line <$fifo_name; then
       # if [[ "$line" == 'ar' ]]; then
        #    break
        #fi
        echo $line
    fi
done

Can anyone help me please? Thank you

Answer

John1024 picture John1024 · Sep 18, 2014

Replace the second script with:

#!/bin/bash    
fifo_name="myfifo"
while true
do
    if read line; then
        echo $line
    fi
done <"$fifo_name"

This opens the fifo only once and reads every line from it.