There is a caveat concerning the reading from a named pipe. When you open a named pipe your open()
call hangs until a writer shows up. When a writer shows up subsequent read()
calls will return whatever data the writer has written to the pipe. However, when the writer closes the pipe (or exits) the read()
calls start returning 0 (rather than blocking).
This is the reason that instead of
int fd = open("testpipe", O_RDONLY);
one might want to open a pipe like this
int fd = open("testpipe", O_RDWR);
This way the process is not only the reader, but also the writer. Even though you never actually write anything to the pipe, this ensures that a writer exists and hence read()
calls do not return 0, but block instead waiting for some writer to write something to the pipe.
Now, when your script does this:
while [ 1 -eq 1 ] do read input ... done < $pipename
your shell opens the pipe for reading only (O_RDONLY
).
The solution to your problem is to make shell open the pipe for both reading and writing like this:
while [ 1 -eq 1 ] do read input ... done <> $pipename
Note the replacement of < $pipename
with <> $pipename
. This is what makes the shell open the pipe for both reading and writing (O_RDWR
).