LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash input/output redirect problem (https://www.linuxquestions.org/questions/programming-9/bash-input-output-redirect-problem-515156/)

greno 12-31-2006 10:46 AM

bash input/output redirect problem
 
Can anyone tell me why the following sometimes works from the command line but refuses to work at all (it hangs) in a shell script file? Is there something buggy about fifo's?
----------------------------
#!/bin/bash
rm /tmp/fifo
mkfifo /tmp/fifo # create fifo
exec 8< /tmp/fifo # open fd 8 for reading
exec 9> /tmp/fifo # open fd 9 for writing
echo fifocontent >&9 & # dump some content to fifo - don't block script
cat <&8 # read content from fifo
----------------------------

bash: 3.1.17(1) on FC6
bash: 2.05b.0(1) on RH9

ta0kira 12-31-2006 03:19 PM

Try putting the exec lines in the background with &. I can't imagine it working on the command line or in the script without the first being in the background.
ta0kira

firstfire 12-31-2006 03:23 PM

Hello!

Command
Code:

exec 8< /tmp/fifo
itself hangs up because FIFO must be opened for reading and writing simultaneously. You can use
Code:

exec  8<>/tmp/fifo
instead, but in this case one can not close only one end of FIFO because both ends are the same. Here is an example:
Code:

#!/bin/bash
rm /tmp/fifo
mkfifo /tmp/fifo
exec 8<> /tmp/fifo
echo fifocontent >&8 &
cat <&8

This script do the work, but hangs up on last command (`cat') because write-end of FIFO (fd 8) not closed (as well as read-end fd=8).

P.S.: putting exec in background can't help because new file descriptor is accessible in subshell only (I think). Following script exhibits this behaviour:
Code:

#!/bin/bash
exec 3>&1 &
echo "test-message"  >&3 # fd 3 is unaccessible if
                        # we  use subshell (&) in
                        # previous line

This script will work if we delete &-sign at the tail of second line.
One can use following approach, though:
Code:

#!/bin/bash
rm /tmp/fifo
mkfifo /tmp/fifo
(exec 9> /tmp/fifo; echo fifocontent >&9)&
(exec 8< /tmp/fifo; cat <&8) &
exit  0;



All times are GMT -5. The time now is 04:48 AM.