Search code examples
bashfifowriter

Write and read from a fifo from two different script


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


Solution

  • 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.