--- AnyEvent/lib/AnyEvent.pm 2008/09/06 07:00:45 1.180 +++ AnyEvent/lib/AnyEvent.pm 2009/05/13 15:19:43 1.210 @@ -8,21 +8,28 @@ use AnyEvent; - my $w = AnyEvent->io (fh => $fh, poll => "r|w", cb => sub { ... }); + # file descriptor readable + my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ... }); + # one-shot or repeating timers my $w = AnyEvent->timer (after => $seconds, cb => sub { ... }); my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ... print AnyEvent->now; # prints current event loop time print AnyEvent->time; # think Time::HiRes::time or simply CORE::time. + # POSIX signal my $w = AnyEvent->signal (signal => "TERM", cb => sub { ... }); + # child process exit my $w = AnyEvent->child (pid => $pid, cb => sub { my ($pid, $status) = @_; ... }); + # called when event loop idle (if applicable) + my $w = AnyEvent->idle (cb => sub { ... }); + my $w = AnyEvent->condvar; # stores whether a condition was flagged $w->send; # wake up current and all future recv's $w->recv; # enters "main loop" till $condvar gets ->send @@ -139,6 +146,12 @@ callback when the event occurs (of course, only when the event model is in control). +Note that B +potentially in use by the event loop (such as C<$_> or C<$[>) and that B<< +callbacks must not C >>. The former is good programming practise in +Perl and the latter stems from the fact that exception handling differs +widely between event loops. + To disable the watcher you have to destroy it (e.g. by setting the variable you store it in to C or otherwise deleting all references to it). @@ -164,11 +177,17 @@ You can create an I/O watcher by calling the C<< AnyEvent->io >> method with the following mandatory key-value pairs as arguments: -C the Perl I (I file descriptor) to watch for events -(AnyEvent might or might not keep a reference to this file handle). C -must be a string that is either C or C, which creates a watcher -waiting for "r"eadable or "w"ritable events, respectively. C is the -callback to invoke each time the file handle becomes ready. +C is the Perl I (I file descriptor) to watch +for events (AnyEvent might or might not keep a reference to this file +handle). Note that only file handles pointing to things for which +non-blocking operation makes sense are allowed. This includes sockets, +most character devices, pipes, fifos and so on, but not for example files +or block devices. + +C must be a string that is either C or C, which creates a +watcher waiting for "r"eadable or "w"ritable events, respectively. + +C is the callback to invoke each time the file handle becomes ready. Although the callback might get passed parameters, their value and presence is undefined and you cannot rely on them. Portable AnyEvent @@ -310,6 +329,21 @@ difference between C<< AnyEvent->time >> and C<< AnyEvent->now >> into account. +=item AnyEvent->now_update + +Some event loops (such as L or L) cache +the current time for each loop iteration (see the discussion of L<< +AnyEvent->now >>, above). + +When a callback runs for a long time (or when the process sleeps), then +this "current" time will differ substantially from the real time, which +might affect timers and time-outs. + +When this is the case, you can call this method, which will update the +event loop's idea of "current time". + +Note that updating the time I cause some events to be handled. + =back =head2 SIGNAL WATCHERS @@ -342,11 +376,18 @@ You can also watch on a child process exit and catch its exit status. The child process is specified by the C argument (if set to C<0>, it -watches for any child process exit). The watcher will trigger as often -as status change for the child are received. This works by installing a -signal handler for C. The callback will be called with the pid -and exit status (as returned by waitpid), so unlike other watcher types, -you I rely on child watcher callback arguments. +watches for any child process exit). The watcher will triggered only when +the child process has finished and an exit status is available, not on +any trace events (stopped/continued). + +The callback will be called with the pid and exit status (as returned by +waitpid), so unlike other watcher types, you I rely on child watcher +callback arguments. + +This watcher type works by installing a signal handler for C, +and since it cannot be shared, nothing else should use SIGCHLD or reap +random child processes (waiting for specific child processes, e.g. inside +C, is just fine). There is a slight catch to child watchers, however: you usually start them I the child process was created, and this means the process could @@ -378,6 +419,41 @@ # do something else, then wait for process exit $done->recv; +=head2 IDLE WATCHERS + +Sometimes there is a need to do something, but it is not so important +to do it instantly, but only when there is nothing better to do. This +"nothing better to do" is usually defined to be "no other events need +attention by the event loop". + +Idle watchers ideally get invoked when the event loop has nothing +better to do, just before it would block the process to wait for new +events. Instead of blocking, the idle watcher is invoked. + +Most event loops unfortunately do not really support idle watchers (only +EV, Event and Glib do it in a usable fashion) - for the rest, AnyEvent +will simply call the callback "from time to time". + +Example: read lines from STDIN, but only process them when the +program is otherwise idle: + + my @lines; # read data + my $idle_w; + my $io_w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub { + push @lines, scalar ; + + # 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; + } + }); + }); + =head2 CONDITION VARIABLES If you are familiar with some event loops you will know that all of them @@ -820,9 +896,9 @@ A non-blocking interface to the Internet Go Server protocol (used by L). -=item L +=item L -AnyEvent based IRC client module family. +AnyEvent based IRC client module family (replacing the older Net::IRC3). =item L @@ -856,7 +932,7 @@ use Carp; -our $VERSION = 4.233; +our $VERSION = 4.41; our $MODEL; our $AUTOLOAD; @@ -898,7 +974,8 @@ [Prima:: => AnyEvent::Impl::POE::], ); -our %method = map +($_ => 1), qw(io timer time now signal child condvar one_event DESTROY); +our %method = map +($_ => 1), + qw(io timer time now now_update signal child idle condvar one_event DESTROY); our @post_detect; @@ -913,12 +990,12 @@ push @post_detect, $cb; defined wantarray - ? bless \$cb, "AnyEvent::Util::PostDetect" + ? bless \$cb, "AnyEvent::Util::postdetect" : () } } -sub AnyEvent::Util::PostDetect::DESTROY { +sub AnyEvent::Util::postdetect::DESTROY { @post_detect = grep $_ != ${$_[0]}, @post_detect; } @@ -965,7 +1042,7 @@ } $MODEL - or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: EV, Event or Glib."; + or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: EV, Event or Glib.\n"; } } @@ -999,15 +1076,13 @@ sub _dupfh($$$$) { my ($poll, $fh, $r, $w) = @_; - require Fcntl; - # cygwin requires the fh mode to be matching, unix doesn't my ($rw, $mode) = $poll eq "r" ? ($r, "<") : $poll eq "w" ? ($w, ">") : Carp::croak "AnyEvent->io requires poll set to either 'r' or 'w'"; open my $fh2, "$mode&" . fileno $fh - or die "cannot dup() filehandle: $!"; + or die "cannot dup() filehandle: $!,"; # we assume CLOEXEC is already set by perl in all important cases @@ -1016,50 +1091,92 @@ package AnyEvent::Base; -# default implementation for now and time +# default implementations for many methods BEGIN { - if (eval "use Time::HiRes (); time (); 1") { + if (eval "use Time::HiRes (); Time::HiRes::time (); 1") { *_time = \&Time::HiRes::time; # if (eval "use POSIX (); (POSIX::times())... } else { - *_time = \&CORE::time; # epic fail + *_time = sub { time }; # epic fail } } sub time { _time } sub now { _time } +sub now_update { } # default implementation for ->condvar sub condvar { - bless { @_ == 3 ? (_ae_cb => $_[2]) : () }, AnyEvent::CondVar:: + bless { @_ == 3 ? (_ae_cb => $_[2]) : () }, "AnyEvent::CondVar" } # default implementation for ->signal -our %SIG_CB; +our ($SIGPIPE_R, $SIGPIPE_W, %SIG_CB, %SIG_EV, $SIG_IO); + +sub _signal_exec { + sysread $SIGPIPE_R, my $dummy, 4; + + while (%SIG_EV) { + for (keys %SIG_EV) { + delete $SIG_EV{$_}; + $_->() for values %{ $SIG_CB{$_} || {} }; + } + } +} sub signal { my (undef, %arg) = @_; + unless ($SIGPIPE_R) { + require Fcntl; + + if (AnyEvent::WIN32) { + require AnyEvent::Util; + + ($SIGPIPE_R, $SIGPIPE_W) = AnyEvent::Util::portable_pipe (); + AnyEvent::Util::fh_nonblocking ($SIGPIPE_R) if $SIGPIPE_R; + AnyEvent::Util::fh_nonblocking ($SIGPIPE_W) if $SIGPIPE_W; # just in case + } else { + pipe $SIGPIPE_R, $SIGPIPE_W; + fcntl $SIGPIPE_R, &Fcntl::F_SETFL, &Fcntl::O_NONBLOCK if $SIGPIPE_R; + fcntl $SIGPIPE_W, &Fcntl::F_SETFL, &Fcntl::O_NONBLOCK if $SIGPIPE_W; # just in case + } + + $SIGPIPE_R + or Carp::croak "AnyEvent: unable to create a signal reporting pipe: $!\n"; + + # not strictly required, as $^F is normally 2, but let's make sure... + fcntl $SIGPIPE_R, &Fcntl::F_SETFD, &Fcntl::FD_CLOEXEC; + fcntl $SIGPIPE_W, &Fcntl::F_SETFD, &Fcntl::FD_CLOEXEC; + + $SIG_IO = AnyEvent->io (fh => $SIGPIPE_R, poll => "r", cb => \&_signal_exec); + } + my $signal = uc $arg{signal} or Carp::croak "required option 'signal' is missing"; $SIG_CB{$signal}{$arg{cb}} = $arg{cb}; $SIG{$signal} ||= sub { - $_->() for values %{ $SIG_CB{$signal} || {} }; + local $!; + syswrite $SIGPIPE_W, "\x00", 1 unless %SIG_EV; + undef $SIG_EV{$signal}; }; - bless [$signal, $arg{cb}], "AnyEvent::Base::Signal" + bless [$signal, $arg{cb}], "AnyEvent::Base::signal" } -sub AnyEvent::Base::Signal::DESTROY { +sub AnyEvent::Base::signal::DESTROY { my ($signal, $cb) = @{$_[0]}; delete $SIG_CB{$signal}{$cb}; - delete $SIG{$signal} unless keys %{ $SIG_CB{$signal} }; + # delete doesn't work with older perls - they then + # print weird messages, or just unconditionally exit + # instead of getting the default action. + undef $SIG{$signal} unless keys %{ $SIG_CB{$signal} }; } # default implementation for ->child @@ -1067,24 +1184,13 @@ our %PID_CB; our $CHLD_W; our $CHLD_DELAY_W; -our $PID_IDLE; our $WNOHANG; -sub _child_wait { +sub _sigchld { while (0 < (my $pid = waitpid -1, $WNOHANG)) { $_->($pid, $?) for (values %{ $PID_CB{$pid} || {} }), (values %{ $PID_CB{0} || {} }); } - - undef $PID_IDLE; -} - -sub _sigchld { - # make sure we deliver these changes "synchronous" with the event loop. - $CHLD_DELAY_W ||= AnyEvent->timer (after => 0, cb => sub { - undef $CHLD_DELAY_W; - &_child_wait; - }); } sub child { @@ -1095,9 +1201,7 @@ $PID_CB{$pid}{$arg{cb}} = $arg{cb}; - unless ($WNOHANG) { - $WNOHANG = eval { local $SIG{__DIE__}; require POSIX; &POSIX::WNOHANG } || 1; - } + $WNOHANG ||= eval { local $SIG{__DIE__}; require POSIX; &POSIX::WNOHANG } || 1; unless ($CHLD_W) { $CHLD_W = AnyEvent->signal (signal => 'CHLD', cb => \&_sigchld); @@ -1105,10 +1209,10 @@ &_sigchld; } - bless [$pid, $arg{cb}], "AnyEvent::Base::Child" + bless [$pid, $arg{cb}], "AnyEvent::Base::child" } -sub AnyEvent::Base::Child::DESTROY { +sub AnyEvent::Base::child::DESTROY { my ($pid, $cb) = @{$_[0]}; delete $PID_CB{$pid}{$cb}; @@ -1117,6 +1221,42 @@ undef $CHLD_W unless keys %PID_CB; } +# idle emulation is done by simply using a timer, regardless +# of whether the process is idle or not, and not letting +# the callback use more than 50% of the time. +sub idle { + my (undef, %arg) = @_; + + my ($cb, $w, $rcb) = $arg{cb}; + + $rcb = sub { + if ($cb) { + $w = _time; + &$cb; + $w = _time - $w; + + # never use more then 50% of the time for the idle watcher, + # within some limits + $w = 0.0001 if $w < 0.0001; + $w = 5 if $w > 5; + + $w = AnyEvent->timer (after => $w, cb => $rcb); + } else { + # clean up... + undef $w; + undef $rcb; + } + }; + + $w = AnyEvent->timer (after => 0.05, cb => $rcb); + + bless \\$cb, "AnyEvent::Base::idle" +} + +sub AnyEvent::Base::idle::DESTROY { + undef $${$_[0]}; +} + package AnyEvent::CondVar; our @ISA = AnyEvent::CondVar::Base::; @@ -1258,7 +1398,7 @@ This variable can effectively be used for denial-of-service attacks against local programs (e.g. when setuid), although the impact is likely -small, as the program has to handle connection errors already- +small, as the program has to handle conenction and other failures anyways. Examples: C - prefer IPv4 over IPv6, but support both and try to use both. C @@ -1528,16 +1668,16 @@ =head3 Results name watchers bytes create invoke destroy comment - EV/EV 400000 244 0.56 0.46 0.31 EV native interface - EV/Any 100000 244 2.50 0.46 0.29 EV + AnyEvent watchers - CoroEV/Any 100000 244 2.49 0.44 0.29 coroutines + Coro::Signal - Perl/Any 100000 513 4.92 0.87 1.12 pure perl implementation - Event/Event 16000 516 31.88 31.30 0.85 Event native interface - Event/Any 16000 590 35.75 31.42 1.08 Event + AnyEvent watchers - Glib/Any 16000 1357 98.22 12.41 54.00 quadratic behaviour - Tk/Any 2000 1860 26.97 67.98 14.00 SEGV with >> 2000 watchers - POE/Event 2000 6644 108.64 736.02 14.73 via POE::Loop::Event - POE/Select 2000 6343 94.13 809.12 565.96 via POE::Loop::Select + EV/EV 400000 224 0.47 0.35 0.27 EV native interface + EV/Any 100000 224 2.88 0.34 0.27 EV + AnyEvent watchers + CoroEV/Any 100000 224 2.85 0.35 0.28 coroutines + Coro::Signal + Perl/Any 100000 452 4.13 0.73 0.95 pure perl implementation + Event/Event 16000 517 32.20 31.80 0.81 Event native interface + Event/Any 16000 590 35.85 31.55 1.06 Event + AnyEvent watchers + Glib/Any 16000 1357 102.33 12.31 51.00 quadratic behaviour + Tk/Any 2000 1860 27.20 66.31 14.00 SEGV with >> 2000 watchers + POE/Event 2000 6328 109.99 751.67 14.02 via POE::Loop::Event + POE/Select 2000 6027 94.54 809.13 579.80 via POE::Loop::Select =head3 Discussion @@ -1749,6 +1889,42 @@ =back +=head1 SIGNALS + +AnyEvent currently installs handlers for these signals: + +=over 4 + +=item SIGCHLD + +A handler for C is installed by AnyEvent's child watcher +emulation for event loops that do not support them natively. Also, some +event loops install a similar handler. + +=item SIGPIPE + +A no-op handler is installed for C when C<$SIG{PIPE}> is C +when AnyEvent gets loaded. + +The rationale for this is that AnyEvent users usually do not really depend +on SIGPIPE delivery (which is purely an optimisation for shell use, or +badly-written programs), but C can cause spurious and rare +program exits as a lot of people do not expect C when writing to +some random socket. + +The rationale for installing a no-op handler as opposed to ignoring it is +that this way, the handler will be restored to defaults on exec. + +Feel free to install your own handler, or reset it to defaults. + +=back + +=cut + +$SIG{PIPE} = sub { } + unless defined $SIG{PIPE}; + + =head1 FORK Most event libraries are not fork-safe. The ones who are usually are @@ -1786,7 +1962,7 @@ Perl 5.8 has numerous memleaks that sometimes hit this module and are hard to work around. If you suffer from memleaks, first upgrade to Perl 5.10 and check wether the leaks still show up. (Perl 5.10.0 has other annoying -mamleaks, such as leaking on C and C but it is usually not as +memleaks, such as leaking on C and C but it is usually not as pronounced).