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

user1084871 picture user1084871 · Dec 7, 2011 · Viewed 28.6k times · Source

I want to output some data to a pipe and have the other process do something to the data line by line. Here is a toy example:

mkfifo pipe
cat pipe&
cat >pipe

Now I can enter whatever I want, and after pressing enter I immediately see the same line. But if substitute second pipe with echo:

mkfifo pipe
cat pipe&
echo "some data" >pipe

The pipe closes after echo and cat pipe& finishes so that I cannot pass any more data through the pipe. Is there a way to avoid closing the pipe and the process that receives the data, so that I can pass many lines of data through the pipe from a bash script and have them processed as they arrive?

Answer

Mark Edgar picture Mark Edgar · Dec 8, 2011

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

# Create pipe and start reader.
mkfifo pipe
cat 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 pipe
cat pipe &
# Open pipe for writing.
exec 3>pipe
echo one >&3
echo two >&3
# Close pipe.
exec 3>&-