Issue
I want to output some data to a pipe and have the other process do something to the data line by line. Here is a toy example:
mkfifo pipe
cat pipe&
cat >pipe
Now I can enter whatever I want, and after pressing enter I immediately see the same line. But if substitute second pipe with echo
:
mkfifo pipe
cat pipe&
echo "some data" >pipe
The pipe closes after echo
and cat pipe&
finishes so that I cannot pass any more data through the pipe. Is there a way to avoid closing the pipe and the process that receives the data, so that I can pass many lines of data through the pipe from a bash script and have them processed as they arrive?
Solution
When a FIFO is opened for reading, it blocks the calling process (normally — unless there is already a process with the FIFO open for writing, in which case, any blocked writers are unblocked). When a process opens the FIFO for writing, then any blocked readers are unblocked (but the process is blocked if there are no readers). When the last writer closes the FIFO, the reading processes get EOF (0 bytes to read), and there is nothing further that can be done except close the FIFO and reopen it. Thus, you need to use a loop:
mkfifo pipe
(while cat pipe; do : Nothing; done &)
echo "some data" > pipe
echo "more data" > pipe
An alternative is to keep some process with the FIFO open.
mkfifo pipe
sleep 10000 > pipe &
cat pipe &
echo "some data" > pipe
echo "more data" > pipe
Answered By - Jonathan Leffler Answer Checked By - Marilyn (WPSolving Volunteer)