在 perl 循环中重定向命名管道

Redirect a Named Pipe in a perl loop

将命名管道作为源

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

为什么下面的命令没有打印出任何消息?

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

同时删除最后一个命令所有 运行 按预期

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

当Perl进程的STDOUT没有连接到tty时,autoflushing被关闭。当将 Perl 进程的输出通过管道传输到 cat 而不是将其打印到终端时就是这种情况。这会导致 cat 命令挂起,等待来自 Perl 进程的输入。

您可以通过为 STDOUT 打开自动刷新来解决此问题:

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

或者您可以使用 unbuffer 命令:

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