ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent.pm
(Generate patch)

Comparing AnyEvent/lib/AnyEvent.pm (file contents):
Revision 1.299 by root, Tue Dec 1 17:53:48 2009 UTC vs.
Revision 1.323 by root, Thu May 20 21:22:20 2010 UTC

7 7
8=head1 SYNOPSIS 8=head1 SYNOPSIS
9 9
10 use AnyEvent; 10 use AnyEvent;
11 11
12 # if you prefer function calls, look at the AE manpage for
13 # an alternative API.
14
12 # file descriptor readable 15 # file handle or descriptor readable
13 my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ... }); 16 my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ... });
14 17
15 # one-shot or repeating timers 18 # one-shot or repeating timers
16 my $w = AnyEvent->timer (after => $seconds, cb => sub { ... }); 19 my $w = AnyEvent->timer (after => $seconds, cb => sub { ... });
17 my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ... 20 my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ...
503 506
504=head2 IDLE WATCHERS 507=head2 IDLE WATCHERS
505 508
506 $w = AnyEvent->idle (cb => <callback>); 509 $w = AnyEvent->idle (cb => <callback>);
507 510
508Sometimes there is a need to do something, but it is not so important 511Repeatedly invoke the callback after the process becomes idle, until
509to do it instantly, but only when there is nothing better to do. This 512either the watcher is destroyed or new events have been detected.
510"nothing better to do" is usually defined to be "no other events need
511attention by the event loop".
512 513
513Idle watchers ideally get invoked when the event loop has nothing 514Idle watchers are useful when there is a need to do something, but it
514better to do, just before it would block the process to wait for new 515is not so important (or wise) to do it instantly. The callback will be
515events. Instead of blocking, the idle watcher is invoked. 516invoked only when there is "nothing better to do", which is usually
517defined as "all outstanding events have been handled and no new events
518have been detected". That means that idle watchers ideally get invoked
519when the event loop has just polled for new events but none have been
520detected. Instead of blocking to wait for more events, the idle watchers
521will be invoked.
516 522
517Most event loops unfortunately do not really support idle watchers (only 523Unfortunately, most event loops do not really support idle watchers (only
518EV, Event and Glib do it in a usable fashion) - for the rest, AnyEvent 524EV, Event and Glib do it in a usable fashion) - for the rest, AnyEvent
519will simply call the callback "from time to time". 525will simply call the callback "from time to time".
520 526
521Example: read lines from STDIN, but only process them when the 527Example: read lines from STDIN, but only process them when the
522program is otherwise idle: 528program is otherwise idle:
603eventually calls C<< -> send >>, and the "consumer side", which waits 609eventually calls C<< -> send >>, and the "consumer side", which waits
604for the send to occur. 610for the send to occur.
605 611
606Example: wait for a timer. 612Example: wait for a timer.
607 613
608 # wait till the result is ready 614 # condition: "wait till the timer is fired"
609 my $result_ready = AnyEvent->condvar; 615 my $timer_fired = AnyEvent->condvar;
610 616
611 # do something such as adding a timer 617 # create the timer - we could wait for, say
612 # or socket watcher the calls $result_ready->send 618 # a handle becomign ready, or even an
613 # when the "result" is ready. 619 # AnyEvent::HTTP request to finish, but
614 # in this case, we simply use a timer: 620 # in this case, we simply use a timer:
615 my $w = AnyEvent->timer ( 621 my $w = AnyEvent->timer (
616 after => 1, 622 after => 1,
617 cb => sub { $result_ready->send }, 623 cb => sub { $timer_fired->send },
618 ); 624 );
619 625
620 # this "blocks" (while handling events) till the callback 626 # this "blocks" (while handling events) till the callback
621 # calls ->send 627 # calls ->send
622 $result_ready->recv; 628 $timer_fired->recv;
623 629
624Example: wait for a timer, but take advantage of the fact that condition 630Example: wait for a timer, but take advantage of the fact that condition
625variables are also callable directly. 631variables are also callable directly.
626 632
627 my $done = AnyEvent->condvar; 633 my $done = AnyEvent->condvar;
966You should check C<$AnyEvent::MODEL> before adding to this array, though: 972You should check C<$AnyEvent::MODEL> before adding to this array, though:
967if it is defined then the event loop has already been detected, and the 973if it is defined then the event loop has already been detected, and the
968array will be ignored. 974array will be ignored.
969 975
970Best use C<AnyEvent::post_detect { BLOCK }> when your application allows 976Best use C<AnyEvent::post_detect { BLOCK }> when your application allows
971it,as it takes care of these details. 977it, as it takes care of these details.
972 978
973This variable is mainly useful for modules that can do something useful 979This variable is mainly useful for modules that can do something useful
974when AnyEvent is used and thus want to know when it is initialised, but do 980when AnyEvent is used and thus want to know when it is initialised, but do
975not need to even load it by default. This array provides the means to hook 981not need to even load it by default. This array provides the means to hook
976into AnyEvent passively, without loading it. 982into AnyEvent passively, without loading it.
983
984Example: To load Coro::AnyEvent whenever Coro and AnyEvent are used
985together, you could put this into Coro (this is the actual code used by
986Coro to accomplish this):
987
988 if (defined $AnyEvent::MODEL) {
989 # AnyEvent already initialised, so load Coro::AnyEvent
990 require Coro::AnyEvent;
991 } else {
992 # AnyEvent not yet initialised, so make sure to load Coro::AnyEvent
993 # as soon as it is
994 push @AnyEvent::post_detect, sub { require Coro::AnyEvent };
995 }
977 996
978=back 997=back
979 998
980=head1 WHAT TO DO IN A MODULE 999=head1 WHAT TO DO IN A MODULE
981 1000
1063 1082
1064=item L<AnyEvent::DNS> 1083=item L<AnyEvent::DNS>
1065 1084
1066Provides rich asynchronous DNS resolver capabilities. 1085Provides rich asynchronous DNS resolver capabilities.
1067 1086
1087=item L<AnyEvent::HTTP>, L<AnyEvent::IRC>, L<AnyEvent::XMPP>, L<AnyEvent::GPSD>, L<AnyEvent::IGS>, L<AnyEvent::FCP>
1088
1089Implement event-based interfaces to the protocols of the same name (for
1090the curious, IGS is the International Go Server and FCP is the Freenet
1091Client Protocol).
1092
1093=item L<AnyEvent::Handle::UDP>
1094
1095Here be danger!
1096
1097As Pauli would put it, "Not only is it not right, it's not even wrong!" -
1098there are so many things wrong with AnyEvent::Handle::UDP, most notably
1099it's use of a stream-based API with a protocol that isn't streamable, that
1100the only way to improve it is to delete it.
1101
1102It features data corruption (but typically only under load) and general
1103confusion. On top, the author is not only clueless about UDP but also
1104fact-resistant - some gems of his understanding: "connect doesn't work
1105with UDP", "UDP packets are not IP packets", "UDP only has datagrams, not
1106packets", "I don't need to implement proper error checking as UDP doesn't
1107support error checking" and so on - he doesn't even understand what's
1108wrong with his module when it is explained to him.
1109
1068=item L<AnyEvent::HTTP> 1110=item L<AnyEvent::DBI>
1069 1111
1070A simple-to-use HTTP library that is capable of making a lot of concurrent 1112Executes L<DBI> requests asynchronously in a proxy process for you,
1071HTTP requests. 1113notifying you in an event-bnased way when the operation is finished.
1114
1115=item L<AnyEvent::AIO>
1116
1117Truly asynchronous (as opposed to non-blocking) I/O, should be in the
1118toolbox of every event programmer. AnyEvent::AIO transparently fuses
1119L<IO::AIO> and AnyEvent together, giving AnyEvent access to event-based
1120file I/O, and much more.
1072 1121
1073=item L<AnyEvent::HTTPD> 1122=item L<AnyEvent::HTTPD>
1074 1123
1075Provides a simple web application server framework. 1124A simple embedded webserver.
1076 1125
1077=item L<AnyEvent::FastPing> 1126=item L<AnyEvent::FastPing>
1078 1127
1079The fastest ping in the west. 1128The fastest ping in the west.
1080
1081=item L<AnyEvent::DBI>
1082
1083Executes L<DBI> requests asynchronously in a proxy process.
1084
1085=item L<AnyEvent::AIO>
1086
1087Truly asynchronous I/O, should be in the toolbox of every event
1088programmer. AnyEvent::AIO transparently fuses L<IO::AIO> and AnyEvent
1089together.
1090
1091=item L<AnyEvent::BDB>
1092
1093Truly asynchronous Berkeley DB access. AnyEvent::BDB transparently fuses
1094L<BDB> and AnyEvent together.
1095
1096=item L<AnyEvent::GPSD>
1097
1098A non-blocking interface to gpsd, a daemon delivering GPS information.
1099
1100=item L<AnyEvent::IRC>
1101
1102AnyEvent based IRC client module family (replacing the older Net::IRC3).
1103
1104=item L<AnyEvent::XMPP>
1105
1106AnyEvent based XMPP (Jabber protocol) module family (replacing the older
1107Net::XMPP2>.
1108
1109=item L<AnyEvent::IGS>
1110
1111A non-blocking interface to the Internet Go Server protocol (used by
1112L<App::IGS>).
1113
1114=item L<Net::FCP>
1115
1116AnyEvent-based implementation of the Freenet Client Protocol, birthplace
1117of AnyEvent.
1118
1119=item L<Event::ExecFlow>
1120
1121High level API for event-based execution flow control.
1122 1129
1123=item L<Coro> 1130=item L<Coro>
1124 1131
1125Has special support for AnyEvent via L<Coro::AnyEvent>. 1132Has special support for AnyEvent via L<Coro::AnyEvent>.
1126 1133
1131package AnyEvent; 1138package AnyEvent;
1132 1139
1133# basically a tuned-down version of common::sense 1140# basically a tuned-down version of common::sense
1134sub common_sense { 1141sub common_sense {
1135 # from common:.sense 1.0 1142 # from common:.sense 1.0
1136 ${^WARNING_BITS} = "\xfc\x3f\xf3\x00\x0f\xf3\xcf\xc0\xf3\xfc\x33\x03"; 1143 ${^WARNING_BITS} = "\xfc\x3f\x33\x00\x0f\xf3\xcf\xc0\xf3\xfc\x33\x00";
1137 # use strict vars subs 1144 # use strict vars subs - NO UTF-8, as Util.pm doesn't like this atm. (uts46data.pl)
1138 $^H |= 0x00000600; 1145 $^H |= 0x00000600;
1139} 1146}
1140 1147
1141BEGIN { AnyEvent::common_sense } 1148BEGIN { AnyEvent::common_sense }
1142 1149
1143use Carp (); 1150use Carp ();
1144 1151
1145our $VERSION = '5.21'; 1152our $VERSION = '5.261';
1146our $MODEL; 1153our $MODEL;
1147 1154
1148our $AUTOLOAD; 1155our $AUTOLOAD;
1149our @ISA; 1156our @ISA;
1150 1157
1151our @REGISTRY; 1158our @REGISTRY;
1152 1159
1153our $VERBOSE; 1160our $VERBOSE;
1154 1161
1155BEGIN { 1162BEGIN {
1156 eval "sub WIN32(){ " . (($^O =~ /mswin32/i)*1) ." }"; 1163 require "AnyEvent/constants.pl";
1164
1157 eval "sub TAINT(){ " . (${^TAINT}*1) . " }"; 1165 eval "sub TAINT (){" . (${^TAINT}*1) . "}";
1158 1166
1159 delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV} 1167 delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV}
1160 if ${^TAINT}; 1168 if ${^TAINT};
1161 1169
1162 $VERBOSE = $ENV{PERL_ANYEVENT_VERBOSE}*1; 1170 $VERBOSE = $ENV{PERL_ANYEVENT_VERBOSE}*1;
1205our @post_detect; 1213our @post_detect;
1206 1214
1207sub post_detect(&) { 1215sub post_detect(&) {
1208 my ($cb) = @_; 1216 my ($cb) = @_;
1209 1217
1210 if ($MODEL) {
1211 $cb->();
1212
1213 undef
1214 } else {
1215 push @post_detect, $cb; 1218 push @post_detect, $cb;
1216 1219
1217 defined wantarray 1220 defined wantarray
1218 ? bless \$cb, "AnyEvent::Util::postdetect" 1221 ? bless \$cb, "AnyEvent::Util::postdetect"
1219 : () 1222 : ()
1220 }
1221} 1223}
1222 1224
1223sub AnyEvent::Util::postdetect::DESTROY { 1225sub AnyEvent::Util::postdetect::DESTROY {
1224 @post_detect = grep $_ != ${$_[0]}, @post_detect; 1226 @post_detect = grep $_ != ${$_[0]}, @post_detect;
1225} 1227}
1226 1228
1227sub detect() { 1229sub detect() {
1230 # free some memory
1231 *detect = sub () { $MODEL };
1232
1233 local $!; # for good measure
1234 local $SIG{__DIE__};
1235
1236 if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z]+)$/) {
1237 my $model = "AnyEvent::Impl::$1";
1238 if (eval "require $model") {
1239 $MODEL = $model;
1240 warn "AnyEvent: loaded model '$model' (forced by \$ENV{PERL_ANYEVENT_MODEL}), using it.\n" if $VERBOSE >= 2;
1241 } else {
1242 warn "AnyEvent: unable to load model '$model' (from \$ENV{PERL_ANYEVENT_MODEL}):\n$@" if $VERBOSE;
1243 }
1244 }
1245
1246 # check for already loaded models
1228 unless ($MODEL) { 1247 unless ($MODEL) {
1229 local $SIG{__DIE__}; 1248 for (@REGISTRY, @models) {
1230 1249 my ($package, $model) = @$_;
1231 if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z]+)$/) { 1250 if (${"$package\::VERSION"} > 0) {
1232 my $model = "AnyEvent::Impl::$1";
1233 if (eval "require $model") { 1251 if (eval "require $model") {
1234 $MODEL = $model; 1252 $MODEL = $model;
1235 warn "AnyEvent: loaded model '$model' (forced by \$ENV{PERL_ANYEVENT_MODEL}), using it.\n" if $VERBOSE >= 2; 1253 warn "AnyEvent: autodetected model '$model', using it.\n" if $VERBOSE >= 2;
1236 } else { 1254 last;
1237 warn "AnyEvent: unable to load model '$model' (from \$ENV{PERL_ANYEVENT_MODEL}):\n$@" if $VERBOSE; 1255 }
1238 } 1256 }
1239 } 1257 }
1240 1258
1241 # check for already loaded models
1242 unless ($MODEL) { 1259 unless ($MODEL) {
1260 # try to autoload a model
1243 for (@REGISTRY, @models) { 1261 for (@REGISTRY, @models) {
1244 my ($package, $model) = @$_; 1262 my ($package, $model, $autoload) = @$_;
1263 if (
1264 $autoload
1265 and eval "require $package"
1245 if (${"$package\::VERSION"} > 0) { 1266 and ${"$package\::VERSION"} > 0
1246 if (eval "require $model") { 1267 and eval "require $model"
1268 ) {
1247 $MODEL = $model; 1269 $MODEL = $model;
1248 warn "AnyEvent: autodetected model '$model', using it.\n" if $VERBOSE >= 2; 1270 warn "AnyEvent: autoloaded model '$model', using it.\n" if $VERBOSE >= 2;
1249 last; 1271 last;
1250 }
1251 } 1272 }
1252 } 1273 }
1253 1274
1254 unless ($MODEL) {
1255 # try to autoload a model
1256 for (@REGISTRY, @models) {
1257 my ($package, $model, $autoload) = @$_;
1258 if (
1259 $autoload
1260 and eval "require $package"
1261 and ${"$package\::VERSION"} > 0
1262 and eval "require $model"
1263 ) {
1264 $MODEL = $model;
1265 warn "AnyEvent: autoloaded model '$model', using it.\n" if $VERBOSE >= 2;
1266 last;
1267 }
1268 }
1269
1270 $MODEL 1275 $MODEL
1271 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: EV, Event or Glib.\n"; 1276 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: EV, Event or Glib.\n";
1272 }
1273 } 1277 }
1274
1275 push @{"$MODEL\::ISA"}, "AnyEvent::Base";
1276
1277 unshift @ISA, $MODEL;
1278
1279 require AnyEvent::Strict if $ENV{PERL_ANYEVENT_STRICT};
1280
1281 (shift @post_detect)->() while @post_detect;
1282 } 1278 }
1279
1280 @models = (); # free probe data
1281
1282 push @{"$MODEL\::ISA"}, "AnyEvent::Base";
1283 unshift @ISA, $MODEL;
1284
1285 # now nuke some methods that are overriden by the backend.
1286 # SUPER is not allowed.
1287 for (qw(time signal child idle)) {
1288 undef &{"AnyEvent::Base::$_"}
1289 if defined &{"$MODEL\::$_"};
1290 }
1291
1292 require AnyEvent::Strict if $ENV{PERL_ANYEVENT_STRICT};
1293
1294 (shift @post_detect)->() while @post_detect;
1295
1296 *post_detect = sub(&) {
1297 shift->();
1298
1299 undef
1300 };
1283 1301
1284 $MODEL 1302 $MODEL
1285} 1303}
1286 1304
1287sub AUTOLOAD { 1305sub AUTOLOAD {
1288 (my $func = $AUTOLOAD) =~ s/.*://; 1306 (my $func = $AUTOLOAD) =~ s/.*://;
1289 1307
1290 $method{$func} 1308 $method{$func}
1291 or Carp::croak "$func: not a valid method for AnyEvent objects"; 1309 or Carp::croak "$func: not a valid AnyEvent class method";
1292 1310
1293 detect unless $MODEL; 1311 detect;
1294 1312
1295 my $class = shift; 1313 my $class = shift;
1296 $class->$func (@_); 1314 $class->$func (@_);
1297} 1315}
1298 1316
1315 1333
1316=head1 SIMPLIFIED AE API 1334=head1 SIMPLIFIED AE API
1317 1335
1318Starting with version 5.0, AnyEvent officially supports a second, much 1336Starting with version 5.0, AnyEvent officially supports a second, much
1319simpler, API that is designed to reduce the calling, typing and memory 1337simpler, API that is designed to reduce the calling, typing and memory
1320overhead. 1338overhead by using function call syntax and a fixed number of parameters.
1321 1339
1322See the L<AE> manpage for details. 1340See the L<AE> manpage for details.
1323 1341
1324=cut 1342=cut
1325 1343
1326package AE; 1344package AE;
1327 1345
1328our $VERSION = $AnyEvent::VERSION; 1346our $VERSION = $AnyEvent::VERSION;
1347
1348# fall back to the main API by default - backends and AnyEvent::Base
1349# implementations can overwrite these.
1329 1350
1330sub io($$$) { 1351sub io($$$) {
1331 AnyEvent->io (fh => $_[0], poll => $_[1] ? "w" : "r", cb => $_[2]) 1352 AnyEvent->io (fh => $_[0], poll => $_[1] ? "w" : "r", cb => $_[2])
1332} 1353}
1333 1354
1365 1386
1366package AnyEvent::Base; 1387package AnyEvent::Base;
1367 1388
1368# default implementations for many methods 1389# default implementations for many methods
1369 1390
1370sub _time() { 1391sub time {
1392 eval q{ # poor man's autoloading {}
1371 # probe for availability of Time::HiRes 1393 # probe for availability of Time::HiRes
1372 if (eval "use Time::HiRes (); Time::HiRes::time (); 1") { 1394 if (eval "use Time::HiRes (); Time::HiRes::time (); 1") {
1373 warn "AnyEvent: using Time::HiRes for sub-second timing accuracy.\n" if $VERBOSE >= 8; 1395 warn "AnyEvent: using Time::HiRes for sub-second timing accuracy.\n" if $VERBOSE >= 8;
1374 *_time = \&Time::HiRes::time; 1396 *AE::time = \&Time::HiRes::time;
1375 # if (eval "use POSIX (); (POSIX::times())... 1397 # if (eval "use POSIX (); (POSIX::times())...
1376 } else { 1398 } else {
1377 warn "AnyEvent: using built-in time(), WARNING, no sub-second resolution!\n" if $VERBOSE; 1399 warn "AnyEvent: using built-in time(), WARNING, no sub-second resolution!\n" if $VERBOSE;
1378 *_time = sub { time }; # epic fail 1400 *AE::time = sub (){ time }; # epic fail
1401 }
1402
1403 *time = sub { AE::time }; # different prototypes
1379 } 1404 };
1405 die if $@;
1380 1406
1381 &_time 1407 &time
1382} 1408}
1383 1409
1384sub time { _time } 1410*now = \&time;
1385sub now { _time } 1411
1386sub now_update { } 1412sub now_update { }
1387 1413
1388# default implementation for ->condvar 1414# default implementation for ->condvar
1389 1415
1390sub condvar { 1416sub condvar {
1417 eval q{ # poor man's autoloading {}
1418 *condvar = sub {
1391 bless { @_ == 3 ? (_ae_cb => $_[2]) : () }, "AnyEvent::CondVar" 1419 bless { @_ == 3 ? (_ae_cb => $_[2]) : () }, "AnyEvent::CondVar"
1420 };
1421
1422 *AE::cv = sub (;&) {
1423 bless { @_ ? (_ae_cb => shift) : () }, "AnyEvent::CondVar"
1424 };
1425 };
1426 die if $@;
1427
1428 &condvar
1392} 1429}
1393 1430
1394# default implementation for ->signal 1431# default implementation for ->signal
1395 1432
1396our $HAVE_ASYNC_INTERRUPT; 1433our $HAVE_ASYNC_INTERRUPT;
1405 1442
1406our ($SIGPIPE_R, $SIGPIPE_W, %SIG_CB, %SIG_EV, $SIG_IO); 1443our ($SIGPIPE_R, $SIGPIPE_W, %SIG_CB, %SIG_EV, $SIG_IO);
1407our (%SIG_ASY, %SIG_ASY_W); 1444our (%SIG_ASY, %SIG_ASY_W);
1408our ($SIG_COUNT, $SIG_TW); 1445our ($SIG_COUNT, $SIG_TW);
1409 1446
1410sub _signal_exec {
1411 $HAVE_ASYNC_INTERRUPT
1412 ? $SIGPIPE_R->drain
1413 : sysread $SIGPIPE_R, (my $dummy), 9;
1414
1415 while (%SIG_EV) {
1416 for (keys %SIG_EV) {
1417 delete $SIG_EV{$_};
1418 $_->() for values %{ $SIG_CB{$_} || {} };
1419 }
1420 }
1421}
1422
1423# install a dummy wakeup watcher to reduce signal catching latency 1447# install a dummy wakeup watcher to reduce signal catching latency
1448# used by Impls
1424sub _sig_add() { 1449sub _sig_add() {
1425 unless ($SIG_COUNT++) { 1450 unless ($SIG_COUNT++) {
1426 # try to align timer on a full-second boundary, if possible 1451 # try to align timer on a full-second boundary, if possible
1427 my $NOW = AE::now; 1452 my $NOW = AE::now;
1428 1453
1438 undef $SIG_TW 1463 undef $SIG_TW
1439 unless --$SIG_COUNT; 1464 unless --$SIG_COUNT;
1440} 1465}
1441 1466
1442our $_sig_name_init; $_sig_name_init = sub { 1467our $_sig_name_init; $_sig_name_init = sub {
1443 eval q{ # poor man's autoloading 1468 eval q{ # poor man's autoloading {}
1444 undef $_sig_name_init; 1469 undef $_sig_name_init;
1445 1470
1446 if (_have_async_interrupt) { 1471 if (_have_async_interrupt) {
1447 *sig2num = \&Async::Interrupt::sig2num; 1472 *sig2num = \&Async::Interrupt::sig2num;
1448 *sig2name = \&Async::Interrupt::sig2name; 1473 *sig2name = \&Async::Interrupt::sig2name;
1480 $SIG_IO = AE::io $SIGPIPE_R->fileno, 0, \&_signal_exec; 1505 $SIG_IO = AE::io $SIGPIPE_R->fileno, 0, \&_signal_exec;
1481 1506
1482 } else { 1507 } else {
1483 warn "AnyEvent: using emulated perl signal handling with latency timer.\n" if $VERBOSE >= 8; 1508 warn "AnyEvent: using emulated perl signal handling with latency timer.\n" if $VERBOSE >= 8;
1484 1509
1485 require Fcntl;
1486
1487 if (AnyEvent::WIN32) { 1510 if (AnyEvent::WIN32) {
1488 require AnyEvent::Util; 1511 require AnyEvent::Util;
1489 1512
1490 ($SIGPIPE_R, $SIGPIPE_W) = AnyEvent::Util::portable_pipe (); 1513 ($SIGPIPE_R, $SIGPIPE_W) = AnyEvent::Util::portable_pipe ();
1491 AnyEvent::Util::fh_nonblocking ($SIGPIPE_R, 1) if $SIGPIPE_R; 1514 AnyEvent::Util::fh_nonblocking ($SIGPIPE_R, 1) if $SIGPIPE_R;
1492 AnyEvent::Util::fh_nonblocking ($SIGPIPE_W, 1) if $SIGPIPE_W; # just in case 1515 AnyEvent::Util::fh_nonblocking ($SIGPIPE_W, 1) if $SIGPIPE_W; # just in case
1493 } else { 1516 } else {
1494 pipe $SIGPIPE_R, $SIGPIPE_W; 1517 pipe $SIGPIPE_R, $SIGPIPE_W;
1495 fcntl $SIGPIPE_R, &Fcntl::F_SETFL, &Fcntl::O_NONBLOCK if $SIGPIPE_R; 1518 fcntl $SIGPIPE_R, AnyEvent::F_SETFL, AnyEvent::O_NONBLOCK if $SIGPIPE_R;
1496 fcntl $SIGPIPE_W, &Fcntl::F_SETFL, &Fcntl::O_NONBLOCK if $SIGPIPE_W; # just in case 1519 fcntl $SIGPIPE_W, AnyEvent::F_SETFL, AnyEvent::O_NONBLOCK if $SIGPIPE_W; # just in case
1497 1520
1498 # not strictly required, as $^F is normally 2, but let's make sure... 1521 # not strictly required, as $^F is normally 2, but let's make sure...
1499 fcntl $SIGPIPE_R, &Fcntl::F_SETFD, &Fcntl::FD_CLOEXEC; 1522 fcntl $SIGPIPE_R, AnyEvent::F_SETFD, AnyEvent::FD_CLOEXEC;
1500 fcntl $SIGPIPE_W, &Fcntl::F_SETFD, &Fcntl::FD_CLOEXEC; 1523 fcntl $SIGPIPE_W, AnyEvent::F_SETFD, AnyEvent::FD_CLOEXEC;
1501 } 1524 }
1502 1525
1503 $SIGPIPE_R 1526 $SIGPIPE_R
1504 or Carp::croak "AnyEvent: unable to create a signal reporting pipe: $!\n"; 1527 or Carp::croak "AnyEvent: unable to create a signal reporting pipe: $!\n";
1505 1528
1506 $SIG_IO = AE::io $SIGPIPE_R, 0, \&_signal_exec; 1529 $SIG_IO = AE::io $SIGPIPE_R, 0, \&_signal_exec;
1507 } 1530 }
1508 1531
1509 *signal = sub { 1532 *signal = $HAVE_ASYNC_INTERRUPT
1533 ? sub {
1510 my (undef, %arg) = @_; 1534 my (undef, %arg) = @_;
1511 1535
1512 my $signal = uc $arg{signal}
1513 or Carp::croak "required option 'signal' is missing";
1514
1515 if ($HAVE_ASYNC_INTERRUPT) {
1516 # async::interrupt 1536 # async::interrupt
1517
1518 $signal = sig2num $signal; 1537 my $signal = sig2num $arg{signal};
1519 $SIG_CB{$signal}{$arg{cb}} = $arg{cb}; 1538 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
1520 1539
1521 $SIG_ASY{$signal} ||= new Async::Interrupt 1540 $SIG_ASY{$signal} ||= new Async::Interrupt
1522 cb => sub { undef $SIG_EV{$signal} }, 1541 cb => sub { undef $SIG_EV{$signal} },
1523 signal => $signal, 1542 signal => $signal,
1524 pipe => [$SIGPIPE_R->filenos], 1543 pipe => [$SIGPIPE_R->filenos],
1525 pipe_autodrain => 0, 1544 pipe_autodrain => 0,
1526 ; 1545 ;
1527 1546
1528 } else { 1547 bless [$signal, $arg{cb}], "AnyEvent::Base::signal"
1548 }
1549 : sub {
1550 my (undef, %arg) = @_;
1551
1529 # pure perl 1552 # pure perl
1530
1531 # AE::Util has been loaded in signal
1532 $signal = sig2name $signal; 1553 my $signal = sig2name $arg{signal};
1533 $SIG_CB{$signal}{$arg{cb}} = $arg{cb}; 1554 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
1534 1555
1535 $SIG{$signal} ||= sub { 1556 $SIG{$signal} ||= sub {
1536 local $!; 1557 local $!;
1537 syswrite $SIGPIPE_W, "\x00", 1 unless %SIG_EV; 1558 syswrite $SIGPIPE_W, "\x00", 1 unless %SIG_EV;
1538 undef $SIG_EV{$signal}; 1559 undef $SIG_EV{$signal};
1539 }; 1560 };
1540 1561
1541 # can't do signal processing without introducing races in pure perl, 1562 # can't do signal processing without introducing races in pure perl,
1542 # so limit the signal latency. 1563 # so limit the signal latency.
1543 _sig_add; 1564 _sig_add;
1544 }
1545 1565
1546 bless [$signal, $arg{cb}], "AnyEvent::Base::signal" 1566 bless [$signal, $arg{cb}], "AnyEvent::Base::signal"
1567 }
1547 }; 1568 ;
1548 1569
1549 *AnyEvent::Base::signal::DESTROY = sub { 1570 *AnyEvent::Base::signal::DESTROY = sub {
1550 my ($signal, $cb) = @{$_[0]}; 1571 my ($signal, $cb) = @{$_[0]};
1551 1572
1552 _sig_del; 1573 _sig_del;
1559 # print weird messages, or just unconditionally exit 1580 # print weird messages, or just unconditionally exit
1560 # instead of getting the default action. 1581 # instead of getting the default action.
1561 undef $SIG{$signal} 1582 undef $SIG{$signal}
1562 unless keys %{ $SIG_CB{$signal} }; 1583 unless keys %{ $SIG_CB{$signal} };
1563 }; 1584 };
1585
1586 *_signal_exec = sub {
1587 $HAVE_ASYNC_INTERRUPT
1588 ? $SIGPIPE_R->drain
1589 : sysread $SIGPIPE_R, (my $dummy), 9;
1590
1591 while (%SIG_EV) {
1592 for (keys %SIG_EV) {
1593 delete $SIG_EV{$_};
1594 $_->() for values %{ $SIG_CB{$_} || {} };
1595 }
1596 }
1597 };
1564 }; 1598 };
1565 die if $@; 1599 die if $@;
1600
1566 &signal 1601 &signal
1567} 1602}
1568 1603
1569# default implementation for ->child 1604# default implementation for ->child
1570 1605
1571our %PID_CB; 1606our %PID_CB;
1572our $CHLD_W; 1607our $CHLD_W;
1573our $CHLD_DELAY_W; 1608our $CHLD_DELAY_W;
1574our $WNOHANG; 1609our $WNOHANG;
1575 1610
1611# used by many Impl's
1576sub _emit_childstatus($$) { 1612sub _emit_childstatus($$) {
1577 my (undef, $rpid, $rstatus) = @_; 1613 my (undef, $rpid, $rstatus) = @_;
1578 1614
1579 $_->($rpid, $rstatus) 1615 $_->($rpid, $rstatus)
1580 for values %{ $PID_CB{$rpid} || {} }, 1616 for values %{ $PID_CB{$rpid} || {} },
1581 values %{ $PID_CB{0} || {} }; 1617 values %{ $PID_CB{0} || {} };
1582} 1618}
1583 1619
1584sub _sigchld {
1585 my $pid;
1586
1587 AnyEvent->_emit_childstatus ($pid, $?)
1588 while ($pid = waitpid -1, $WNOHANG) > 0;
1589}
1590
1591sub child { 1620sub child {
1621 eval q{ # poor man's autoloading {}
1622 *_sigchld = sub {
1623 my $pid;
1624
1625 AnyEvent->_emit_childstatus ($pid, $?)
1626 while ($pid = waitpid -1, $WNOHANG) > 0;
1627 };
1628
1629 *child = sub {
1592 my (undef, %arg) = @_; 1630 my (undef, %arg) = @_;
1593 1631
1594 defined (my $pid = $arg{pid} + 0) 1632 defined (my $pid = $arg{pid} + 0)
1595 or Carp::croak "required option 'pid' is missing"; 1633 or Carp::croak "required option 'pid' is missing";
1596 1634
1597 $PID_CB{$pid}{$arg{cb}} = $arg{cb}; 1635 $PID_CB{$pid}{$arg{cb}} = $arg{cb};
1598 1636
1599 # WNOHANG is almost cetrainly 1 everywhere 1637 # WNOHANG is almost cetrainly 1 everywhere
1600 $WNOHANG ||= $^O =~ /^(?:openbsd|netbsd|linux|freebsd|cygwin|MSWin32)$/ 1638 $WNOHANG ||= $^O =~ /^(?:openbsd|netbsd|linux|freebsd|cygwin|MSWin32)$/
1601 ? 1 1639 ? 1
1602 : eval { local $SIG{__DIE__}; require POSIX; &POSIX::WNOHANG } || 1; 1640 : eval { local $SIG{__DIE__}; require POSIX; &POSIX::WNOHANG } || 1;
1603 1641
1604 unless ($CHLD_W) { 1642 unless ($CHLD_W) {
1605 $CHLD_W = AE::signal CHLD => \&_sigchld; 1643 $CHLD_W = AE::signal CHLD => \&_sigchld;
1606 # child could be a zombie already, so make at least one round 1644 # child could be a zombie already, so make at least one round
1607 &_sigchld; 1645 &_sigchld;
1608 } 1646 }
1609 1647
1610 bless [$pid, $arg{cb}], "AnyEvent::Base::child" 1648 bless [$pid, $arg{cb}], "AnyEvent::Base::child"
1611} 1649 };
1612 1650
1613sub AnyEvent::Base::child::DESTROY { 1651 *AnyEvent::Base::child::DESTROY = sub {
1614 my ($pid, $cb) = @{$_[0]}; 1652 my ($pid, $cb) = @{$_[0]};
1615 1653
1616 delete $PID_CB{$pid}{$cb}; 1654 delete $PID_CB{$pid}{$cb};
1617 delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} }; 1655 delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} };
1618 1656
1619 undef $CHLD_W unless keys %PID_CB; 1657 undef $CHLD_W unless keys %PID_CB;
1658 };
1659 };
1660 die if $@;
1661
1662 &child
1620} 1663}
1621 1664
1622# idle emulation is done by simply using a timer, regardless 1665# idle emulation is done by simply using a timer, regardless
1623# of whether the process is idle or not, and not letting 1666# of whether the process is idle or not, and not letting
1624# the callback use more than 50% of the time. 1667# the callback use more than 50% of the time.
1625sub idle { 1668sub idle {
1669 eval q{ # poor man's autoloading {}
1670 *idle = sub {
1626 my (undef, %arg) = @_; 1671 my (undef, %arg) = @_;
1627 1672
1628 my ($cb, $w, $rcb) = $arg{cb}; 1673 my ($cb, $w, $rcb) = $arg{cb};
1629 1674
1630 $rcb = sub { 1675 $rcb = sub {
1631 if ($cb) { 1676 if ($cb) {
1632 $w = _time; 1677 $w = _time;
1633 &$cb; 1678 &$cb;
1634 $w = _time - $w; 1679 $w = _time - $w;
1635 1680
1636 # never use more then 50% of the time for the idle watcher, 1681 # never use more then 50% of the time for the idle watcher,
1637 # within some limits 1682 # within some limits
1638 $w = 0.0001 if $w < 0.0001; 1683 $w = 0.0001 if $w < 0.0001;
1639 $w = 5 if $w > 5; 1684 $w = 5 if $w > 5;
1640 1685
1641 $w = AE::timer $w, 0, $rcb; 1686 $w = AE::timer $w, 0, $rcb;
1642 } else { 1687 } else {
1643 # clean up... 1688 # clean up...
1644 undef $w; 1689 undef $w;
1645 undef $rcb; 1690 undef $rcb;
1691 }
1692 };
1693
1694 $w = AE::timer 0.05, 0, $rcb;
1695
1696 bless \\$cb, "AnyEvent::Base::idle"
1646 } 1697 };
1698
1699 *AnyEvent::Base::idle::DESTROY = sub {
1700 undef $${$_[0]};
1701 };
1647 }; 1702 };
1703 die if $@;
1648 1704
1649 $w = AE::timer 0.05, 0, $rcb; 1705 &idle
1650
1651 bless \\$cb, "AnyEvent::Base::idle"
1652}
1653
1654sub AnyEvent::Base::idle::DESTROY {
1655 undef $${$_[0]};
1656} 1706}
1657 1707
1658package AnyEvent::CondVar; 1708package AnyEvent::CondVar;
1659 1709
1660our @ISA = AnyEvent::CondVar::Base::; 1710our @ISA = AnyEvent::CondVar::Base::;
2019 2069
2020The actual code goes further and collects all errors (C<die>s, exceptions) 2070The actual code goes further and collects all errors (C<die>s, exceptions)
2021that occurred during request processing. The C<result> method detects 2071that occurred during request processing. The C<result> method detects
2022whether an exception as thrown (it is stored inside the $txn object) 2072whether an exception as thrown (it is stored inside the $txn object)
2023and just throws the exception, which means connection errors and other 2073and just throws the exception, which means connection errors and other
2024problems get reported tot he code that tries to use the result, not in a 2074problems get reported to the code that tries to use the result, not in a
2025random callback. 2075random callback.
2026 2076
2027All of this enables the following usage styles: 2077All of this enables the following usage styles:
2028 2078
20291. Blocking: 20791. Blocking:
2448it's built-in modules) are required to use it. 2498it's built-in modules) are required to use it.
2449 2499
2450That does not mean that AnyEvent won't take advantage of some additional 2500That does not mean that AnyEvent won't take advantage of some additional
2451modules if they are installed. 2501modules if they are installed.
2452 2502
2453This section epxlains which additional modules will be used, and how they 2503This section explains which additional modules will be used, and how they
2454affect AnyEvent's operation. 2504affect AnyEvent's operation.
2455 2505
2456=over 4 2506=over 4
2457 2507
2458=item L<Async::Interrupt> 2508=item L<Async::Interrupt>
2464catch the signals) with some delay (default is 10 seconds, look for 2514catch the signals) with some delay (default is 10 seconds, look for
2465C<$AnyEvent::MAX_SIGNAL_LATENCY>). 2515C<$AnyEvent::MAX_SIGNAL_LATENCY>).
2466 2516
2467If this module is available, then it will be used to implement signal 2517If this module is available, then it will be used to implement signal
2468catching, which means that signals will not be delayed, and the event loop 2518catching, which means that signals will not be delayed, and the event loop
2469will not be interrupted regularly, which is more efficient (And good for 2519will not be interrupted regularly, which is more efficient (and good for
2470battery life on laptops). 2520battery life on laptops).
2471 2521
2472This affects not just the pure-perl event loop, but also other event loops 2522This affects not just the pure-perl event loop, but also other event loops
2473that have no signal handling on their own (e.g. Glib, Tk, Qt). 2523that have no signal handling on their own (e.g. Glib, Tk, Qt).
2474 2524
2486automatic timer adjustments even when no monotonic clock is available, 2536automatic timer adjustments even when no monotonic clock is available,
2487can take avdantage of advanced kernel interfaces such as C<epoll> and 2537can take avdantage of advanced kernel interfaces such as C<epoll> and
2488C<kqueue>, and is the fastest backend I<by far>. You can even embed 2538C<kqueue>, and is the fastest backend I<by far>. You can even embed
2489L<Glib>/L<Gtk2> in it (or vice versa, see L<EV::Glib> and L<Glib::EV>). 2539L<Glib>/L<Gtk2> in it (or vice versa, see L<EV::Glib> and L<Glib::EV>).
2490 2540
2541If you only use backends that rely on another event loop (e.g. C<Tk>),
2542then this module will do nothing for you.
2543
2491=item L<Guard> 2544=item L<Guard>
2492 2545
2493The guard module, when used, will be used to implement 2546The guard module, when used, will be used to implement
2494C<AnyEvent::Util::guard>. This speeds up guards considerably (and uses a 2547C<AnyEvent::Util::guard>. This speeds up guards considerably (and uses a
2495lot less memory), but otherwise doesn't affect guard operation much. It is 2548lot less memory), but otherwise doesn't affect guard operation much. It is
2496purely used for performance. 2549purely used for performance.
2497 2550
2498=item L<JSON> and L<JSON::XS> 2551=item L<JSON> and L<JSON::XS>
2499 2552
2500One of these modules is required when you want to read or write JSON data 2553One of these modules is required when you want to read or write JSON data
2501via L<AnyEvent::Handle>. It is also written in pure-perl, but can take 2554via L<AnyEvent::Handle>. L<JSON> is also written in pure-perl, but can take
2502advantage of the ultra-high-speed L<JSON::XS> module when it is installed. 2555advantage of the ultra-high-speed L<JSON::XS> module when it is installed.
2503
2504In fact, L<AnyEvent::Handle> will use L<JSON::XS> by default if it is
2505installed.
2506 2556
2507=item L<Net::SSLeay> 2557=item L<Net::SSLeay>
2508 2558
2509Implementing TLS/SSL in Perl is certainly interesting, but not very 2559Implementing TLS/SSL in Perl is certainly interesting, but not very
2510worthwhile: If this module is installed, then L<AnyEvent::Handle> (with 2560worthwhile: If this module is installed, then L<AnyEvent::Handle> (with
2521 2571
2522 2572
2523=head1 FORK 2573=head1 FORK
2524 2574
2525Most event libraries are not fork-safe. The ones who are usually are 2575Most event libraries are not fork-safe. The ones who are usually are
2526because they rely on inefficient but fork-safe C<select> or C<poll> 2576because they rely on inefficient but fork-safe C<select> or C<poll> calls
2527calls. Only L<EV> is fully fork-aware. 2577- higher performance APIs such as BSD's kqueue or the dreaded Linux epoll
2578are usually badly thought-out hacks that are incompatible with fork in
2579one way or another. Only L<EV> is fully fork-aware and ensures that you
2580continue event-processing in both parent and child (or both, if you know
2581what you are doing).
2582
2583This means that, in general, you cannot fork and do event processing in
2584the child if the event library was initialised before the fork (which
2585usually happens when the first AnyEvent watcher is created, or the library
2586is loaded).
2528 2587
2529If you have to fork, you must either do so I<before> creating your first 2588If you have to fork, you must either do so I<before> creating your first
2530watcher OR you must not use AnyEvent at all in the child OR you must do 2589watcher OR you must not use AnyEvent at all in the child OR you must do
2531something completely out of the scope of AnyEvent. 2590something completely out of the scope of AnyEvent.
2591
2592The problem of doing event processing in the parent I<and> the child
2593is much more complicated: even for backends that I<are> fork-aware or
2594fork-safe, their behaviour is not usually what you want: fork clones all
2595watchers, that means all timers, I/O watchers etc. are active in both
2596parent and child, which is almost never what you want. USing C<exec>
2597to start worker children from some kind of manage rprocess is usually
2598preferred, because it is much easier and cleaner, at the expense of having
2599to have another binary.
2532 2600
2533 2601
2534=head1 SECURITY CONSIDERATIONS 2602=head1 SECURITY CONSIDERATIONS
2535 2603
2536AnyEvent can be forced to load any event model via 2604AnyEvent can be forced to load any event model via

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines