How to avoid echo closing FIFO named pipes? - Funny behavior of Unix FIFOs How to avoid echo closing FIFO named pipes? - Funny behavior of Unix FIFOs bash bash

How to avoid echo closing FIFO named pipes? - Funny behavior of Unix FIFOs


Put all the statements you want to output to the fifo in the same subshell:

# Create pipe and start reader.mkfifo pipecat pipe &# Write to pipe.(  echo one  echo two) >pipe

If you have some more complexity, you can open the pipe for writing:

# Create pipe and start reader.mkfifo pipecat pipe &# Open pipe for writing.exec 3>pipeecho one >&3echo two >&3# Close pipe.exec 3>&-


When a FIFO is opened for reading, it blocks the calling process (normally). When a process opens the FIFO for writing, then the reader is unblocked. When the writer closes the FIFO, the reading process gets EOF (0 bytes to read), and there is nothing further that can be done except close the FIFO and reopen. Thus, you need to use a loop:

mkfifo pipe(while cat pipe; do : Nothing; done &)echo "some data" > pipeecho "more data" > pipe

An alternative is to keep some process with the FIFO open.

mkfifo pipesleep 10000 > pipe &cat pipe &echo "some data" > pipeecho "more data" > pipe


You can solve this very easily by opening the read side of the pipe in read-write mode. The reader only gets an EOF once the last writer closes. So opening it in read-write makes sure there is always at least one writer.

So change your second example to:

mkfifo pipecat <>pipe &echo "some data" >pipe