简体   繁体   English

管道Perl脚本输出到head -n 10打印10行后会杀死脚本

[英]Piping Perl script output to head -n 10 kills script after printing 10 lines

My Perl script outputs and logs many lines of text, and it does some cleanup and compresses some logs in an END block. 我的Perl脚本输出并记录了许多行文本,并进行了一些清理并压缩了END块中的一些日志。

The problem is when you do something like this on the command line: 问题是当您在命令行上执行以下操作时:

perl myscript.pl | head -n 10

This causes the script to die as soon as it outputs 10 lines, so the END block doesn't get executed and the logs don't get compressed. 这会导致脚本在输出10行时立即死亡,因此END块不会被执行并且日志不会被压缩。 Is there a way to get around this and make sure the code in my END block is still executed? 有没有办法绕过这个并确保我的END块中的代码仍然执行?

When the reading end of a pipe is closed, and the writing process tries to write something to a pipe, then the writing process receives a SIGPIPE . 当管道的读取端关闭,并且写入过程试图将某些东西写入管道时,写入过程会收到一个SIGPIPE The pipe is called broken . 管道被称为破碎

We can capture this event like 我们可以抓住这个事件

local $SIG{PIPE} = sub {
  # This is our event handler.
  warn "Broken pipe, will exit\n";
  exit 1;
};

This would gracefully exit your program. 这将优雅地退出您的程序。 Instead of installing a sub as event handler, you could give the string IGNORE . 您可以给字符串IGNORE ,而不是将子作为事件处理程序安装。 This would let your script carry on as if nothing happened. 这会让你的脚本继续运行,好像什么也没发生。

# print will now return false with $!{EPIPE} true instead of dying
local $SIG{PIPE} = 'IGNORE';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM