766
Comment: thanks to the one who submitted the fd solution, it's great.
|
1173
converted to 1.6 markup
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
[[Anchor(faq85)]] | <<Anchor(faq85)>> |
Line 4: | Line 4: |
The basic use of named pipes is: | The basic use of NamedPipes is: |
Line 6: | Line 6: |
mkfifo myfifo | |
Line 9: | Line 10: |
this works but, cat dies after it. What if we want to write several times to the pipe without having to reopen it? | |
Line 11: | Line 11: |
If the commands are consecutive, they can be grouped inside a subshell and redirect it's output: | This works, but `cat` dies after reading one line. (In fact, what happens is each time the named pipe is closed by the ''writer'', this signals an end of file condition for the ''reader''. So `cat`, the reader, terminates because it saw the end of its input.) What if we want to write several times to the pipe without having to restart the reader? We have to arrange for all our data to be sent without opening and closing the pipe multiple times. If the commands are consecutive, they can be grouped: |
Line 14: | Line 18: |
(echo 'a'; echo 'b'; echo 'c';) > myfifo | { echo 'a'; echo 'b'; echo 'c'; } > myfifo |
Line 24: | Line 28: |
# writing to fd 3 instead of the pipe | # writing to fd 3 instead of reopening the pipe |
Line 32: | Line 36: |
Closing the fd causes the pipe's reader to receive the end of file indication. |
How to write several times to a fifo without having to reopen it?
The basic use of NamedPipes is:
mkfifo myfifo cat < myfifo & echo 'a' > myfifo
This works, but cat dies after reading one line. (In fact, what happens is each time the named pipe is closed by the writer, this signals an end of file condition for the reader. So cat, the reader, terminates because it saw the end of its input.)
What if we want to write several times to the pipe without having to restart the reader? We have to arrange for all our data to be sent without opening and closing the pipe multiple times.
If the commands are consecutive, they can be grouped:
cat < myfifo & { echo 'a'; echo 'b'; echo 'c'; } > myfifo
But if they can't be grouped for some reason, a better way is to assign a file descriptor to the pipe and write there:
cat < myfifo & # assigning fd 3 to the pipe exec 3>myfifo # writing to fd 3 instead of reopening the pipe echo 'a' >&3 echo 'b' >&3 echo 'c' >&3 # closing the fd exec 3>&-
Closing the fd causes the pipe's reader to receive the end of file indication.