Perl AnyEvent中的watcher实例

2019-10-01 11:30:44王旭

    cb => sub {
        say AnyEvent->time ," ",AnyEvent->now ;
        exit 1 ;
 
    }
);
 
$cv->recv;

child watcher


#!/usr/bin/perl
use AnyEvent;
   my $done = AnyEvent->condvar;
 
   my $pid = fork or exit 5;
 
   my $w = AnyEvent->child (
      pid => $pid,
      cb  => sub {
         my ($pid, $status) = @_;
         warn "pid $pid exited with status $status";
         $done->send;
      },
   );
 
   # do something else, then wait for process exit
   $done->recv;

idle watcher

就是如果main loop在空闲的时候做些什么呢?


#!/usr/bin/perl
use AnyEvent;
   my @lines; # read data
   my $idle_w;
   $cv = AnyEvent->condvar;
   my $io_w = AnyEvent->io (fh => *STDIN, poll => 'r', cb => sub {
      push @lines, scalar <STDIN>;
 
      # start an idle watcher, if not already done
      $idle_w ||= AnyEvent->idle (cb => sub {
         # handle only one line, when there are lines left
         if (my $line = shift @lines) {
            print "handled when idle: $line";
         } else {
            # otherwise disable the idle watcher again
            undef $idle_w;
         }
      });
   });
 
   $cv->recv;