You can create a named pipe using the
mkfifocommand, which creates a special pipe file that remains in place until it is removed. Since it is a type of file, you can use the
rmcommand to remove it when you are done.
sharfah@firefly:~> mkfifo mypipe sharfah@firefly:~> ls mypipe|Writing to a named pipe
Since a named pipe is just a special type of file, you can write to it just as you would normally write to a file. However, if there are no processes reading from the pipe, the write call will block. The following example script writes numbers into the pipe. If there are no readers, it will block on line 5.
COUNT=1 while (true) do echo Writer$$: $COUNT echo $COUNT > mypipe COUNT=`expr $COUNT + 1` sleep 1 doneReading from a named pipe
Reading from a named pipe is the same as reading from a normal file. You can
cata named pipe,
readit as follows:
while (true) do read line < mypipe echo Reader$$: $line doneMultiple readers
If you have multiple readers reading from the same pipe, only one of the readers will receive the output. This is illustrated with the following example, in which I have launched one writer and two readers:
sharfah@firefly:~> writer.sh& reader.sh& reader.sh& Writer10500: 1 Reader10501: 1 Writer10500: 2 Reader10502: Reader10501: 2 Writer10500: 3 Reader10501: 3 Reader10502: Writer10500: 4 Reader10501: Reader10502: 4 Writer10500: 5 Reader10502: 5 Reader10501: Writer10500: 6 Reader10501: 6 Reader10502: Writer10500: 7 Reader10502: 7 Reader10501: Writer10500: 8 Reader10502: 8 Reader10501: Writer10500: 9 Reader10501: 9 Reader10502: Writer10500: 10 Reader10502: 10