Writing and reading from fifo from two different script

I have two bash script. One script will write in fifo. The second is read from fifo, but AFTER the first end for writing.

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

The first script is (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; 

Second script (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 anybody help me? Thanks you

+8
bash writer fifo
source share
3 answers

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 fifo only once and reads each line from it.

+6
source share

The problem with your setup is that you have the creation of fifo in the wrong script if you want to control access to the fifo file while the program is running. To fix the problem, you need to do something like this:

reader: fifo_read.sh

 #!/bin/bash fifo_name="/tmp/myfifo" # fifo name trap "rm -f $fifo_name" EXIT # set trap to rm fifo_name at exit [ -p "$fifo_name" ] || mkfifo "$fifo_name" # if fifo not found, create exec 3< $fifo_name # redirect fifo_name to fd 3 # (not required, but makes read clearer) while :; do if read -r -u 3 line; then # read line from fifo_name if [ "$line" = 'quit' ]; then # if line is quit, quit printf "%s: 'quit' command received\n" "$fifo_name" break fi printf "%s: %s\n" "$fifo_name" "$line" # print line read fi done exec 3<&- # reset fd 3 redirection exit 0 

writer: fifo_write.sh

 #!/bin/bash fifo_name="/tmp/myfifo" # Se non esiste, exit :); [ -p "$fifo_name" ] || { printf "\n Error fifo '%s' not found.\n\n" "$fifo_name" exit 1 } [ -n "$1" ] && printf "%s\n" "$1" > "$fifo_name" || printf "pid: '%s' writing to fifo\n" "$$" > "$fifo_name" exit 0 

: (start reading in terminal 1)

 $ ./fifo_read.sh # you can background with & at end 

(startup script in the second terminal)

 $ ./fifo_write.sh "message from writer" # second terminal $ ./fifo_write.sh $ ./fifo_write.sh quit 

output in terminal 1:

 $ ./fifo_read.sh /tmp/myfifo: message from writer /tmp/myfifo: pid: '28698' writing to fifo /tmp/myfifo: 'quit' command received 
+2
source share

The following script should complete the task:

 #!/bin/bash FIFO="/tmp/fifo" if [ ! -e "$FIFO" ]; then mkfifo "$FIFO" fi for script in "$@"; do echo $script > $FIFO & done while read script; do /bin/bash -c $script done < $FIFO 

Considering the two scripts a.sh and b.sh, where both scripts pass "a" and "b" to stdout, respectively, we get the following result (given that the above script is called test.sh):

 ./test.sh /tmp/a.sh /tmp/b.sh a b 

Best, Julian

0
source share

All Articles