title: AnyEvent file writes plus logrotate lead to unexpected file sizes
body: <p>I have a script that writes out to a file on a frequent basis using AnyEvent. I've written the following sample to illustrate the issue I'm facing.</p>
  
  <pre><code>#!/usr/bin/perl
  
  use strict;
  use warnings;
  
  use AnyEvent;
  use AnyEvent::Handle;
  
  my $outputFile = 'out_test.log';
  open my $out, "&gt;&gt;", $outputFile or die "Can't open output\n";
  
  my $data = "test string"x50000 . "\n";
  
  my $out_ready = AnyEvent-&gt;condvar;
  my $out_hdl; $out_hdl = AnyEvent::Handle-&gt;new(
      fh =&gt; $out,
      on_error =&gt; sub {
          my ($hdl, $fatal, $msg) = @_;
          AE::log error =&gt; $msg;
          $hdl-&gt;destroy;
          $out_ready-&gt;send;
      }
  );
  
  my $timer = AnyEvent-&gt;timer(
      after =&gt; 0,
      interval =&gt; 5,
      cb =&gt; sub {
          $out_hdl-&gt;push_write($data);
      }
  );
  
  $out_ready-&gt;recv;
  </code></pre>
  
  <p>This works well, but the file size gets to be enormous after a while. We use logrotate for problems like this so I created the following logrotate configuration file.</p>
  
  <pre><code>/path/to/out_test.log {
          size 2M
          copytruncate
          rotate 4
  }
  </code></pre>
  
  <p>This also works well, and any time the above output file exceeds 2M it is rotated to out_test.log.1. However, when out_test.log is written to immediately after rotation, the file size is the same as the rotated log file. This behavior and what I'm experiencing is explained here: <a href="https://serverfault.com/a/221343">https://serverfault.com/a/221343</a></p>
  
  <p>While I understand the issue, I don't know how to fix the problem in the sample Perl code I provided.</p>
  
  <p>I don't have to implement log rotation via logrotate, but it would be preferred. If it's simple to implement in the script I can do that, but it would be nice if I could make the above sample play nice with logrotate. Any help or comments are appreciated. Thanks!</p>
  
  <p>EDIT</p>
  
  <p>Based on the answers below I was able to get things working with the monkeypatch ikegami provided as well as leveraging native perl I/O as per Marc Lehmann's advice. My example code looks like this and works well. Additionally this removes the requirement for the copytruncate directive in logrotate.</p>
  
  <pre><code>#!/usr/bin/perl
  
  use strict;
  use warnings;
  
  use AnyEvent;
  use AnyEvent::Handle;
  
  my $outputFile = 'out_test.log';
  open my $out, "&gt;&gt;", $outputFile or die "Can't open output\n";
  
  my $data = "test string"x50000 . "\n";
  
  my $cv = AnyEvent::condvar();
  my $timer = AnyEvent-&gt;timer(
      after =&gt; 0,
      interval =&gt; 5,
      cb =&gt; sub {
          open my $out, "&gt;&gt;", $outputFile or die "Can't open output\n";
          print $out $data;
          close $out; 
      }
  );
  
  $cv-&gt;recv;
  </code></pre>