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.241 by root, Fri Jul 17 18:08:35 2009 UTC vs.
Revision 1.243 by root, Fri Jul 17 23:12:20 2009 UTC

361invocation, and callback invocation will be synchronous. Synchronous means 361invocation, and callback invocation will be synchronous. Synchronous means
362that it might take a while until the signal gets handled by the process, 362that it might take a while until the signal gets handled by the process,
363but it is guaranteed not to interrupt any other callbacks. 363but it is guaranteed not to interrupt any other callbacks.
364 364
365The main advantage of using these watchers is that you can share a signal 365The main advantage of using these watchers is that you can share a signal
366between multiple watchers. 366between multiple watchers, and AnyEvent will ensure that signals will not
367interrupt your program at bad times.
367 368
368This watcher might use C<%SIG>, so programs overwriting those signals 369This watcher might use C<%SIG> (depending on the event loop used),
369directly will likely not work correctly. 370so programs overwriting those signals directly will likely not work
371correctly.
372
373Also note that many event loops (e.g. Glib, Tk, Qt, IO::Async) do not
374support attaching callbacks to signals, which is a pity, as you cannot do
375race-free signal handling in perl. AnyEvent will try to do it's best, but
376in some cases, signals will be delayed. The maximum time a signal might
377be delayed is specified in C<$AnyEvent::MAX_SIGNAL_LATENCY> (default: 10
378seconds). This variable can be changed only before the first signal
379watcher is created, and should be left alone otherwise. Higher values
380will cause fewer spurious wake-ups, which is better for power and CPU
381saving. All these problems can be avoided by installing the optional
382L<Async::Interrupt> module.
370 383
371Example: exit on SIGINT 384Example: exit on SIGINT
372 385
373 my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 }); 386 my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
374 387
403 416
404This means you cannot create a child watcher as the very first 417This means you cannot create a child watcher as the very first
405thing in an AnyEvent program, you I<have> to create at least one 418thing in an AnyEvent program, you I<have> to create at least one
406watcher before you C<fork> the child (alternatively, you can call 419watcher before you C<fork> the child (alternatively, you can call
407C<AnyEvent::detect>). 420C<AnyEvent::detect>).
421
422As most event loops do not support waiting for child events, they will be
423emulated by AnyEvent in most cases, in which the latency and race problems
424mentioned in the description of signal watchers apply.
408 425
409Example: fork a process and wait for it 426Example: fork a process and wait for it
410 427
411 my $done = AnyEvent->condvar; 428 my $done = AnyEvent->condvar;
412 429
1024 1041
1025=cut 1042=cut
1026 1043
1027package AnyEvent; 1044package AnyEvent;
1028 1045
1046# basically a tuned-down version of common::sense
1047sub common_sense {
1029no warnings; 1048 # no warnings
1049 ${^WARNING_BITS} ^= ${^WARNING_BITS};
1030use strict qw(vars subs); 1050 # use strict vars subs
1051 $^H |= 0x00000600;
1052}
1053
1054BEGIN { AnyEvent::common_sense }
1031 1055
1032use Carp (); 1056use Carp ();
1033 1057
1034our $VERSION = 4.83; 1058our $VERSION = 4.83;
1035our $MODEL; 1059our $MODEL;
1038our @ISA; 1062our @ISA;
1039 1063
1040our @REGISTRY; 1064our @REGISTRY;
1041 1065
1042our $WIN32; 1066our $WIN32;
1067
1068our $VERBOSE;
1043 1069
1044BEGIN { 1070BEGIN {
1045 eval "sub WIN32(){ " . (($^O =~ /mswin32/i)*1) ." }"; 1071 eval "sub WIN32(){ " . (($^O =~ /mswin32/i)*1) ." }";
1046 eval "sub TAINT(){ " . (${^TAINT}*1) . " }"; 1072 eval "sub TAINT(){ " . (${^TAINT}*1) . " }";
1047 1073
1048 delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV} 1074 delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV}
1049 if ${^TAINT}; 1075 if ${^TAINT};
1050}
1051 1076
1052our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1; 1077 $VERBOSE = $ENV{PERL_ANYEVENT_VERBOSE}*1;
1078
1079}
1080
1081our $MAX_SIGNAL_LATENCY = 10;
1053 1082
1054our %PROTOCOL; # (ipv4|ipv6) => (1|2), higher numbers are preferred 1083our %PROTOCOL; # (ipv4|ipv6) => (1|2), higher numbers are preferred
1055 1084
1056{ 1085{
1057 my $idx; 1086 my $idx;
1108 @post_detect = grep $_ != ${$_[0]}, @post_detect; 1137 @post_detect = grep $_ != ${$_[0]}, @post_detect;
1109} 1138}
1110 1139
1111sub detect() { 1140sub detect() {
1112 unless ($MODEL) { 1141 unless ($MODEL) {
1113 no strict 'refs';
1114 local $SIG{__DIE__}; 1142 local $SIG{__DIE__};
1115 1143
1116 if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z]+)$/) { 1144 if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z]+)$/) {
1117 my $model = "AnyEvent::Impl::$1"; 1145 my $model = "AnyEvent::Impl::$1";
1118 if (eval "require $model") { 1146 if (eval "require $model") {
1119 $MODEL = $model; 1147 $MODEL = $model;
1120 warn "AnyEvent: loaded model '$model' (forced by \$ENV{PERL_ANYEVENT_MODEL}), using it.\n" if $verbose > 1; 1148 warn "AnyEvent: loaded model '$model' (forced by \$ENV{PERL_ANYEVENT_MODEL}), using it.\n" if $VERBOSE >= 2;
1121 } else { 1149 } else {
1122 warn "AnyEvent: unable to load model '$model' (from \$ENV{PERL_ANYEVENT_MODEL}):\n$@" if $verbose; 1150 warn "AnyEvent: unable to load model '$model' (from \$ENV{PERL_ANYEVENT_MODEL}):\n$@" if $VERBOSE;
1123 } 1151 }
1124 } 1152 }
1125 1153
1126 # check for already loaded models 1154 # check for already loaded models
1127 unless ($MODEL) { 1155 unless ($MODEL) {
1128 for (@REGISTRY, @models) { 1156 for (@REGISTRY, @models) {
1129 my ($package, $model) = @$_; 1157 my ($package, $model) = @$_;
1130 if (${"$package\::VERSION"} > 0) { 1158 if (${"$package\::VERSION"} > 0) {
1131 if (eval "require $model") { 1159 if (eval "require $model") {
1132 $MODEL = $model; 1160 $MODEL = $model;
1133 warn "AnyEvent: autodetected model '$model', using it.\n" if $verbose > 1; 1161 warn "AnyEvent: autodetected model '$model', using it.\n" if $VERBOSE >= 2;
1134 last; 1162 last;
1135 } 1163 }
1136 } 1164 }
1137 } 1165 }
1138 1166
1143 my ($package, $model) = @$_; 1171 my ($package, $model) = @$_;
1144 if (eval "require $package" 1172 if (eval "require $package"
1145 and ${"$package\::VERSION"} > 0 1173 and ${"$package\::VERSION"} > 0
1146 and eval "require $model") { 1174 and eval "require $model") {
1147 $MODEL = $model; 1175 $MODEL = $model;
1148 warn "AnyEvent: autoprobed model '$model', using it.\n" if $verbose > 1; 1176 warn "AnyEvent: autoprobed model '$model', using it.\n" if $VERBOSE >= 2;
1149 last; 1177 last;
1150 } 1178 }
1151 } 1179 }
1152 1180
1153 $MODEL 1181 $MODEL
1198 1226
1199package AnyEvent::Base; 1227package AnyEvent::Base;
1200 1228
1201# default implementations for many methods 1229# default implementations for many methods
1202 1230
1203BEGIN { 1231sub _time {
1232 # probe for availability of Time::HiRes
1204 if (eval "use Time::HiRes (); Time::HiRes::time (); 1") { 1233 if (eval "use Time::HiRes (); Time::HiRes::time (); 1") {
1234 warn "AnyEvent: using Time::HiRes for sub-second timing accuracy.\n" if $VERBOSE >= 8;
1205 *_time = \&Time::HiRes::time; 1235 *_time = \&Time::HiRes::time;
1206 # if (eval "use POSIX (); (POSIX::times())... 1236 # if (eval "use POSIX (); (POSIX::times())...
1207 } else { 1237 } else {
1238 warn "AnyEvent: using built-in time(), WARNING, no sub-second resolution!\n" if $VERBOSE;
1208 *_time = sub { time }; # epic fail 1239 *_time = sub { time }; # epic fail
1209 } 1240 }
1241
1242 &_time
1210} 1243}
1211 1244
1212sub time { _time } 1245sub time { _time }
1213sub now { _time } 1246sub now { _time }
1214sub now_update { } 1247sub now_update { }
1219 bless { @_ == 3 ? (_ae_cb => $_[2]) : () }, "AnyEvent::CondVar" 1252 bless { @_ == 3 ? (_ae_cb => $_[2]) : () }, "AnyEvent::CondVar"
1220} 1253}
1221 1254
1222# default implementation for ->signal 1255# default implementation for ->signal
1223 1256
1257our $HAVE_ASYNC_INTERRUPT;
1224our ($SIGPIPE_R, $SIGPIPE_W, %SIG_CB, %SIG_EV, $SIG_IO); 1258our ($SIGPIPE_R, $SIGPIPE_W, %SIG_CB, %SIG_EV, $SIG_IO);
1259our (%SIG_ASY, %SIG_ASY_W);
1260our ($SIG_COUNT, $SIG_TW);
1225 1261
1226sub _signal_exec { 1262sub _signal_exec {
1263 $HAVE_ASYNC_INTERRUPT
1264 ? $SIGPIPE_R->drain
1227 sysread $SIGPIPE_R, my $dummy, 4; 1265 : sysread $SIGPIPE_R, my $dummy, 9;
1228 1266
1229 while (%SIG_EV) { 1267 while (%SIG_EV) {
1230 for (keys %SIG_EV) { 1268 for (keys %SIG_EV) {
1231 delete $SIG_EV{$_}; 1269 delete $SIG_EV{$_};
1232 $_->() for values %{ $SIG_CB{$_} || {} }; 1270 $_->() for values %{ $SIG_CB{$_} || {} };
1233 } 1271 }
1234 } 1272 }
1235} 1273}
1236 1274
1275sub _signal {
1276 my (undef, %arg) = @_;
1277
1278 my $signal = uc $arg{signal}
1279 or Carp::croak "required option 'signal' is missing";
1280
1281 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
1282
1283 if ($HAVE_ASYNC_INTERRUPT) {
1284 # async::interrupt
1285
1286 $SIG_ASY{$signal} ||= do {
1287 my $asy = new Async::Interrupt
1288 cb => sub { undef $SIG_EV{$signal} },
1289 signal => $signal,
1290 pipe => [$SIGPIPE_R->filenos],
1291 ;
1292 $asy->pipe_autodrain (0);
1293
1294 $asy
1295 };
1296
1297 } else {
1298 # pure perl
1299
1300 $SIG{$signal} ||= sub {
1301 local $!;
1302 syswrite $SIGPIPE_W, "\x00", 1 unless %SIG_EV;
1303 undef $SIG_EV{$signal};
1304 };
1305
1306 # can't do signal processing without introducing races in pure perl,
1307 # so limit the signal latency.
1308 ++$SIG_COUNT;
1309 $SIG_TW ||= AnyEvent->timer (
1310 after => $MAX_SIGNAL_LATENCY,
1311 interval => $MAX_SIGNAL_LATENCY,
1312 cb => sub { }, # just for the PERL_ASYNC_CHECK
1313 );
1314 }
1315
1316 bless [$signal, $arg{cb}], "AnyEvent::Base::signal"
1317}
1318
1237sub signal { 1319sub signal {
1238 my (undef, %arg) = @_; 1320 # probe for availability of Async::Interrupt
1321 if (!$ENV{PERL_ANYEVENT_AVOID_ASYNC_INTERRUPT} && eval "use Async::Interrupt 0.6 (); 1") {
1322 warn "AnyEvent: using Async::Interrupt for race-free signal handling.\n" if $VERBOSE >= 8;
1239 1323
1240 unless ($SIGPIPE_R) { 1324 $HAVE_ASYNC_INTERRUPT = 1;
1325 $SIGPIPE_R = new Async::Interrupt::EventPipe;
1326 $SIG_IO = AnyEvent->io (fh => $SIGPIPE_R->fileno, poll => "r", cb => \&_signal_exec);
1327
1328 } else {
1329 warn "AnyEvent: using emulated perl signal handling with latency timer.\n" if $VERBOSE >= 8;
1330
1241 require Fcntl; 1331 require Fcntl;
1242 1332
1243 if (AnyEvent::WIN32) { 1333 if (AnyEvent::WIN32) {
1244 require AnyEvent::Util; 1334 require AnyEvent::Util;
1245 1335
1260 or Carp::croak "AnyEvent: unable to create a signal reporting pipe: $!\n"; 1350 or Carp::croak "AnyEvent: unable to create a signal reporting pipe: $!\n";
1261 1351
1262 $SIG_IO = AnyEvent->io (fh => $SIGPIPE_R, poll => "r", cb => \&_signal_exec); 1352 $SIG_IO = AnyEvent->io (fh => $SIGPIPE_R, poll => "r", cb => \&_signal_exec);
1263 } 1353 }
1264 1354
1265 my $signal = uc $arg{signal} 1355 *signal = \&_signal;
1266 or Carp::croak "required option 'signal' is missing"; 1356 &signal
1267
1268 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
1269 $SIG{$signal} ||= sub {
1270 local $!;
1271 syswrite $SIGPIPE_W, "\x00", 1 unless %SIG_EV;
1272 undef $SIG_EV{$signal};
1273 };
1274
1275 bless [$signal, $arg{cb}], "AnyEvent::Base::signal"
1276} 1357}
1277 1358
1278sub AnyEvent::Base::signal::DESTROY { 1359sub AnyEvent::Base::signal::DESTROY {
1279 my ($signal, $cb) = @{$_[0]}; 1360 my ($signal, $cb) = @{$_[0]};
1361
1362 undef $SIG_TW
1363 unless --$SIG_COUNT;
1280 1364
1281 delete $SIG_CB{$signal}{$cb}; 1365 delete $SIG_CB{$signal}{$cb};
1282 1366
1283 # delete doesn't work with older perls - they then 1367 # delete doesn't work with older perls - they then
1284 # print weird messages, or just unconditionally exit 1368 # print weird messages, or just unconditionally exit
1285 # instead of getting the default action. 1369 # instead of getting the default action.
1370 undef $SIG{$signal}
1286 undef $SIG{$signal} unless keys %{ $SIG_CB{$signal} }; 1371 unless keys %{ $SIG_CB{$signal} };
1287} 1372}
1288 1373
1289# default implementation for ->child 1374# default implementation for ->child
1290 1375
1291our %PID_CB; 1376our %PID_CB;
1293our $CHLD_DELAY_W; 1378our $CHLD_DELAY_W;
1294our $WNOHANG; 1379our $WNOHANG;
1295 1380
1296sub _sigchld { 1381sub _sigchld {
1297 while (0 < (my $pid = waitpid -1, $WNOHANG)) { 1382 while (0 < (my $pid = waitpid -1, $WNOHANG)) {
1383 $_->($pid, $?)
1298 $_->($pid, $?) for (values %{ $PID_CB{$pid} || {} }), 1384 for values %{ $PID_CB{$pid} || {} },
1299 (values %{ $PID_CB{0} || {} }); 1385 values %{ $PID_CB{0} || {} };
1300 } 1386 }
1301} 1387}
1302 1388
1303sub child { 1389sub child {
1304 my (undef, %arg) = @_; 1390 my (undef, %arg) = @_;
1306 defined (my $pid = $arg{pid} + 0) 1392 defined (my $pid = $arg{pid} + 0)
1307 or Carp::croak "required option 'pid' is missing"; 1393 or Carp::croak "required option 'pid' is missing";
1308 1394
1309 $PID_CB{$pid}{$arg{cb}} = $arg{cb}; 1395 $PID_CB{$pid}{$arg{cb}} = $arg{cb};
1310 1396
1397 # WNOHANG is almost cetrainly 1 everywhere
1398 $WNOHANG ||= $^O =~ /^(?:openbsd|netbsd|linux|freebsd|cygwin|MSWin32)$/
1399 ? 1
1311 $WNOHANG ||= eval { local $SIG{__DIE__}; require POSIX; &POSIX::WNOHANG } || 1; 1400 : eval { local $SIG{__DIE__}; require POSIX; &POSIX::WNOHANG } || 1;
1312 1401
1313 unless ($CHLD_W) { 1402 unless ($CHLD_W) {
1314 $CHLD_W = AnyEvent->signal (signal => 'CHLD', cb => \&_sigchld); 1403 $CHLD_W = AnyEvent->signal (signal => 'CHLD', cb => \&_sigchld);
1315 # child could be a zombie already, so make at least one round 1404 # child could be a zombie already, so make at least one round
1316 &_sigchld; 1405 &_sigchld;
1368 1457
1369our @ISA = AnyEvent::CondVar::Base::; 1458our @ISA = AnyEvent::CondVar::Base::;
1370 1459
1371package AnyEvent::CondVar::Base; 1460package AnyEvent::CondVar::Base;
1372 1461
1373use overload 1462#use overload
1374 '&{}' => sub { my $self = shift; sub { $self->send (@_) } }, 1463# '&{}' => sub { my $self = shift; sub { $self->send (@_) } },
1375 fallback => 1; 1464# fallback => 1;
1465
1466# save 300+ kilobytes by dirtily hardcoding overloading
1467${"AnyEvent::CondVar::Base::OVERLOAD"}{dummy}++; # Register with magic by touching.
1468*{'AnyEvent::CondVar::Base::()'} = sub { }; # "Make it findable via fetchmethod."
1469*{'AnyEvent::CondVar::Base::(&{}'} = sub { my $self = shift; sub { $self->send (@_) } }; # &{}
1470${'AnyEvent::CondVar::Base::()'} = 1; # fallback
1376 1471
1377our $WAITING; 1472our $WAITING;
1378 1473
1379sub _send { 1474sub _send {
1380 # nop 1475 # nop
1481check the arguments passed to most method calls. If it finds any problems, 1576check the arguments passed to most method calls. If it finds any problems,
1482it will croak. 1577it will croak.
1483 1578
1484In other words, enables "strict" mode. 1579In other words, enables "strict" mode.
1485 1580
1486Unlike C<use strict>, it is definitely recommended to keep it off in 1581Unlike C<use strict> (or it's modern cousin, C<< use L<common::sense>
1487production. Keeping C<PERL_ANYEVENT_STRICT=1> in your environment while 1582>>, it is definitely recommended to keep it off in production. Keeping
1488developing programs can be very useful, however. 1583C<PERL_ANYEVENT_STRICT=1> in your environment while developing programs
1584can be very useful, however.
1489 1585
1490=item C<PERL_ANYEVENT_MODEL> 1586=item C<PERL_ANYEVENT_MODEL>
1491 1587
1492This can be used to specify the event model to be used by AnyEvent, before 1588This can be used to specify the event model to be used by AnyEvent, before
1493auto detection and -probing kicks in. It must be a string consisting 1589auto detection and -probing kicks in. It must be a string consisting
2132 if $SIG{CHLD} eq 'IGNORE'; 2228 if $SIG{CHLD} eq 'IGNORE';
2133 2229
2134$SIG{PIPE} = sub { } 2230$SIG{PIPE} = sub { }
2135 unless defined $SIG{PIPE}; 2231 unless defined $SIG{PIPE};
2136 2232
2233=head1 RECOMMENDED/OPTIONAL MODULES
2234
2235One of AnyEvent's main goals is to be 100% Pure-Perl(tm): only perl (and
2236it's built-in modules) are required to use it.
2237
2238That does not mean that AnyEvent won't take advantage of some additional
2239modules if they are installed.
2240
2241This section epxlains which additional modules will be used, and how they
2242affect AnyEvent's operetion.
2243
2244=over 4
2245
2246=item L<Async::Interrupt>
2247
2248This slightly arcane module is used to implement fast signal handling: To
2249my knowledge, there is no way to do completely race-free and quick
2250signal handling in pure perl. To ensure that signals still get
2251delivered, AnyEvent will start an interval timer to wake up perl (and
2252catch the signals) with soemd elay (default is 10 seconds, look for
2253C<$AnyEvent::MAX_SIGNAL_LATENCY>).
2254
2255If this module is available, then it will be used to implement signal
2256catching, which means that signals will not be delayed, and the event loop
2257will not be interrupted regularly, which is more efficient (And good for
2258battery life on laptops).
2259
2260This affects not just the pure-perl event loop, but also other event loops
2261that have no signal handling on their own (e.g. Glib, Tk, Qt).
2262
2263=item L<EV>
2264
2265This module isn't really "optional", as it is simply one of the backend
2266event loops that AnyEvent can use. However, it is simply the best event
2267loop available in terms of features, speed and stability: It supports
2268the AnyEvent API optimally, implements all the watcher types in XS, does
2269automatic timer adjustments even when no monotonic clock is available,
2270can take avdantage of advanced kernel interfaces such as C<epoll> and
2271C<kqueue>, and is the fastest backend I<by far>. You can even embed
2272L<Glib>/L<Gtk2> in it (or vice versa, see L<EV::Glib> and L<Glib::EV>).
2273
2274=item L<Guard>
2275
2276The guard module, when used, will be used to implement
2277C<AnyEvent::Util::guard>. This speeds up guards considerably (and uses a
2278lot less memory), but otherwise doesn't affect guard operation much. It is
2279purely used for performance.
2280
2281=item L<JSON> and L<JSON::XS>
2282
2283This module is required when you want to read or write JSON data via
2284L<AnyEvent::Handle>. It is also written in pure-perl, but can take
2285advantage of the ulta-high-speed L<JSON::XS> module when it is installed.
2286
2287In fact, L<AnyEvent::Handle> will use L<JSON::XS> by default if it is
2288installed.
2289
2290=item L<Net::SSLeay>
2291
2292Implementing TLS/SSL in Perl is certainly interesting, but not very
2293worthwhile: If this module is installed, then L<AnyEvent::Handle> (with
2294the help of L<AnyEvent::TLS>), gains the ability to do TLS/SSL.
2295
2296=item L<Time::HiRes>
2297
2298This module is part of perl since release 5.008. It will be used when the
2299chosen event library does not come with a timing source on it's own. The
2300pure-perl event loop (L<AnyEvent::Impl::Perl>) will additionally use it to
2301try to use a monotonic clock for timing stability.
2302
2303=back
2304
2305
2137=head1 FORK 2306=head1 FORK
2138 2307
2139Most event libraries are not fork-safe. The ones who are usually are 2308Most event libraries are not fork-safe. The ones who are usually are
2140because they rely on inefficient but fork-safe C<select> or C<poll> 2309because they rely on inefficient but fork-safe C<select> or C<poll>
2141calls. Only L<EV> is fully fork-aware. 2310calls. Only L<EV> is fully fork-aware.
2142 2311
2143If you have to fork, you must either do so I<before> creating your first 2312If you have to fork, you must either do so I<before> creating your first
2144watcher OR you must not use AnyEvent at all in the child. 2313watcher OR you must not use AnyEvent at all in the child OR you must do
2314something completely out of the scope of AnyEvent.
2145 2315
2146 2316
2147=head1 SECURITY CONSIDERATIONS 2317=head1 SECURITY CONSIDERATIONS
2148 2318
2149AnyEvent can be forced to load any event model via 2319AnyEvent can be forced to load any event model via

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines