I'm on linux and I originally expected that for a fifo file, when I dump some content into it by a writer, the writer will wait for read peer to read "all" its content and then return. But seems not as I expected, I had a simple experiment:
First of all, I created a fifo file:
$mkfifo hfifo.txt
Then I had a "my.txt" file, having several lines":
$cat my.txt
line1
line2
line3
line4
I open a "tty1" to write to hfifo.txt with my.txt:
cat my.txt >hfifo.txt
I open another terminal "tty2",to read one line from it:
$read l1<hfifo.txt
Well to my supprise, as "read" finishes, the "cat" in my "tty1" also returns immediately. I "echo $l1" will print "line1". This is quite weird to me because I expected that the reader peer should read all the content being writen to the fifo, and then the writer peer(tty1) will return. But the actual result is, once the reader peer ends, writer peer also ends.
I am just curious
(1) how the writer peer know that there's no more reader to read the fifo so it finishes? I could be in a loop to call the "read" command to print each line of this file.
(2) Beside "cat" command as a reader to dump the fifo, is there a way for shell programming to read this fifo one line by one line?
Please kindly suggest, thanks!
'strace' comes in handy. You can see the following lines for file with 3 characters + newline:
read(3, "qqq\n", 131072) = 4
write(1, "qqq\n", 4) = 4
read(3, "", 131072) = 0
As you can see, both read() and write() return the number of characters read, and on the last interation return zero, which signals the process has ended.
regardins (2) There are commands that do other things, like sed awk and egrep that also read the file line by line, but to just read the file, AFAIK only cat.