Pregunta

My Perl script outputs and logs many lines of text, and it does some cleanup and compresses some logs in an END block.

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. Is there a way to get around this and make sure the code in my END block is still executed?

¿Fue útil?

Solución

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. 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. 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';
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top