The process reading from a named pipe will normally terminate when the process writing to the pipe finishes writing (sends an EOF). In certain situations you may have different processes writing intermittently to the pipe, and want a single process to continuously read from the pipe. To do this you can set up a 'dummy' writer that opens the pipe but doesn't write to it:
$ mkfifo myPipe
$ cat > myPipe &
The dummy writer keeps the named pipe open — without feeding data into it or ever closing. The reader process is thus able to receive input from all of the (other) legitimate writers without terminating and having to be respawned.
I have seen some folks use exec 3>
instead of cat
as a way to keep the named pipe open.
$ mkfifo myPipe
$ cat < myPipe &
[1] 10796
$ exec 3> myPipe
$ echo "blah" > myPipe
blah
This approach seems to work, and you don't have a dummy writer in the background to worry about (or clean up), so I like it. The problem is that I don't really understand it.
How is exec 3>
accomplishing the task of keeping the named pipe open without an actual file to be executed, or a visible (background) process, and are there any downsides to this approach?
(I know that it must ultimately be opening the named pipe's input file descriptor for writing, so I'm specifically interested in what the exec 3
part of exec 3>
is doing.)
echo "blah" > myPipe
, you could alsoecho "blah" >&3
too, becauseecho
inherits the open file descriptor 3 from the shell.exec 3> myPipe
.