Search code examples
bashperlpipenamed-pipes

Redirect a Named Pipe in a perl loop


Having a named pipe as a source

shell1> mkfifo ~/myfifo
shell1> tee -a ~/myfifo
ciao

Why doesn't the following command print out any message?

shell2> cat ~/myfifo | perl -ane 'print "testa\n"' | cat

Whilst removing the last command all run as supposed

shell2> cat ~/myfifo | perl -ane 'print "testa\n"'
testa

Solution

  • When the STDOUT of the Perl process is not connected to a tty, autoflushing is turned off. This is the case when piping the output from the Perl process to cat instead of printing it to the terminal. This causes the cat command to hang, waiting for input from the Perl process.

    You can fix this by turning on autoflush for STDOUT:

    cat ~/myfifo | perl -ane 'STDOUT->autoflush(1); print "testa\n"' | cat 
    

    alternativly you can use the unbuffer command:

    cat ~/myfifo | unbuffer -p perl -ane 'print "testa\n"' | cat