Bug 31836

Summary: When killed Perl should flush output buffers
Product: Base System Reporter: Alejandro Forero Cuervo <bachue>
Component: binAssignee: freebsd-bugs (Nobody) <bugs>
Status: Closed FIXED    
Severity: Affects Only Me    
Priority: Normal    
Version: 4.4-RELEASE   
Hardware: Any   
OS: Any   

Description Alejandro Forero Cuervo 2001-11-08 01:10:01 UTC
When the Perl interpreter is killed with SIGINT or SIGTERM (and probably many
other trappable signals), it doesn't flush its output buffers.

By default, when someone calls Perl's print function, it performs unbuffered
writes.  When a Perl script exits, Perl does the right thing: it flushes the
output buffers.  However, when the Perl interpreter is killed, it doesn't flush
them.

This is confusing to many users (I just helped one in the spanish users'
mailing list) and forces them to call the autoflush method from IO::Handle or
set $| to 1 (to disable buffering) when all they really want is just to have
their streams flushed.

This doesn't affect GNU/Linux (Debian using Perl 5.6.0).  However, I have
tested it in OpenBSD and (unsurprisingly) it is also affected.

The Perl interpreter should catch most (all?  Hmm, what happens with SIGSEGV or
SIGBUS?  Hmm) trapable signals and automagically flush output buffers when they
are about to cause program termination.

I'm not sure if this is the right place to report this problem.  If I'm doing
something wrong, please forgive me and let me know so, in my efforts to help
FreeBSD, I no longer do it in the future.

Fix: 

This doesn't fix the problem but is what the users have to do to get around it:
add
    $|=1;
at the beginning or their scripts or use IO::Handle's autoflush method.
How-To-Repeat: The following Perl script should illustrate well what happens:

    for ($i = 0; $i ne 10; $i ++) {
      sleep(1);
      print "!";
    }

When the user runs it, it exits after 10 seconds and the Perl interpreter
flushes the output buffer so the user sees "!!!!!!!!!!".

However, if the user interrupts the script (by, for instance, pressing C-c),
Perl does not flush the output buffer and the user sees nothing.
Comment 1 Anton Berezin freebsd_committer freebsd_triage 2001-11-10 17:20:40 UTC
State Changed
From-To: open->closed

> When the Perl interpreter is killed with SIGINT or SIGTERM (and 
> probably many other trappable signals), it doesn't flush its output 
> buffers. 

It should not.  If you want this functionality, set your own signal 
handlers ($SIG{INT} = sub { ... }; $SIG{TERM} = sub { ... };).  It is 
not the job of the interpreter to do this.  Perl, just like C, uses 
stdio, which is buffered by default.  In C, just like in Perl, you will 
have to set your own signal handlers if you want to flush the buffers on 
a signal.