Prevent automatic EOFs to a named pipe, and send an EOF when I want it

As others have indicated, the reader of a pipe receives EOF once there are no writers left. So the solution is to make sure there is always one writer holding it open. That writer doesn't have to send anything, just hold it open.

Since you're using a shell script, the simplest solution is to tell the shell to open the pipe for writing. And then close it when you're done.

#!/bin/sh
mkfifo P
exec 3>P # open file descriptor 3 writing to the pipe
program < P
# < P tail -n +1 -f | program
echo some stuff > P
cat more_stuff.txt > P
exec 3>&- # close file descriptor 3

Note that if you omit the last line, file descriptor 3 will be automatically closed (and thus the reader receive EOF) when the script exits. Aside from convenience, this also provides a safety of sorts if the script were to somehow terminate early.


A pipe receives EOF when the last writer goes away. To avoid this, make sure that there is always a writer (a process that has the pipe open for writing, but doesn't actually write anything). To send the EOF, make that reserve writer go away.

mkfifo P
while sleep 1; do :; done >P &
P_writer_pid=$!
send_eof_to_P () {
  kill $P_writer_pid
}