Search code examples
bashpipemkfifo

Bash howto write/read to/from a named pipe without aborting after first sending


GIVEN:

Bash command line (Terminal 1):

 > mkfifo pipo
 > cat pipo

Bash command line (Terminal 2):

 > echo -e "Hello World\nHi" > pipo

RESULT:

The bash in (Terminal 1) prints:

 Hello World
 Hi

and aborts.

QUESTION:

How can I achieve that it does not abort, but allows to send another echo through pipo?


Solution

  • It's because echo ... > fifo opens and then closes the fifo. As a workaround you can do like this:

    # open for writing
    exec 20> fifo
    echo foo >&20
    echo bar >&20
    ...
    # to close it
    exec 20>&-
    

    A bit explanation:

    • exec 20> fifo opens fifo for writing with FD (file descriptor) 20.
    • command >&20 redirects the output to FD 20.
    • exec 20>&- closes FD 20.

    The following are excerpts from man bash:

    • exec [-cl] [-a name] [command [arguments]]

      [...] If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1.

    • [n]>word

      Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size. [...]

    • [n]>&word

      [...] If word evaluates to -, file descriptor n is closed. [...]