How are named and unnamed pipes different, and what might be the advantages of using one type of pipe over the other?
A named pipe (technically a FIFO special file) is a unidirectional abstraction for interprocess communication. It shares a number of properties with a regular pipe, such as the ability providing a bounded buffer to send a byte stream of data from one process to another.
Using Named Pipes§
To create a FIFO, you use the mkfifo(1) command which internally uses the mkfifo(3) system call:
$ mkfifo npipe
FIFOs appear as entries in the directory in which they are created with a p
type:
$ ls -l npipe
prw-r--r-- 1 gback cs3214 0 Feb 14 09:12 npipe
They are subject to standard Unix permissions.
After having been created, named pipes can be used as IPC devices. For instance, you can run
$ tail -f npipe
in one terminal and in another
$ echo "Hello Pipe" > npipe
which will result in Hello Pipe
being printed in the first.
Note that while FIFO can be created in NFS file space,
they will not work across different machines in a cluster.
Comparison to Pipes§
Although named pipes and pipes are similar, they exhibit the following differences which lead to differences in their use:
-
Named pipes have an entry in the file system which must be created first. Regular pipes do not have named entries in the filesystem, and thus there is no need for processes to agree on what the name should be and where (in which directory) the entry should be located.
-
Named pipes must be removed when they are no longer needed. By contrast, regular pipes are automatically reclaimed when all processes referring to them have terminated (or have closed the file descriptors referring to the pipe).
-
Named pipes allow unrelated processes to communicate with each other if they know the name and location of the pipe. By contrast, regular pipes require that all communicating processes have a shared ancestor process (often a shell) that creates the pipe for them and passes on file descriptors that refer to the pipe.
-
Named pipes can be reused for multiple IPC exchanges. By contrast a regular pipe is destroyed once all file descriptors referring to it are closed.
-
Named pipes are created with
mkfifo(3)
and opened withopen(2)
whereas pipes are created withpipe(2)
.