1package POE::Kernel; 2 3use strict; 4 5use vars qw($VERSION); 6$VERSION = '1.368'; # NOTE - Should be #.### (three decimal places) 7 8use POE::Resource::Clock qw( monotime sleep mono2wall wall2mono walltime time ); 9 10use POSIX qw(uname); 11use Errno qw(ESRCH EINTR ECHILD EPERM EINVAL EEXIST EAGAIN EWOULDBLOCK); 12use Carp qw(carp croak confess cluck); 13use Sys::Hostname qw(hostname); 14use IO::Handle (); 15use File::Spec (); 16#use Time::HiRes qw(time sleep); 17 18# People expect these to be lexical. 19 20use vars qw($poe_kernel $poe_main_window); 21 22#------------------------------------------------------------------------------ 23# A cheezy exporter to avoid using Exporter. 24 25my $queue_class; 26 27BEGIN { 28 eval { 29 require POE::XS::Queue::Array; 30 POE::XS::Queue::Array->import(); 31 $queue_class = "POE::XS::Queue::Array"; 32 }; 33 unless ($queue_class) { 34 require POE::Queue::Array; 35 POE::Queue::Array->import(); 36 $queue_class = "POE::Queue::Array"; 37 } 38} 39 40sub import { 41 my ($class, $args) = ($poe_kernel, @_[1..$#_]); 42 my $package = caller(); 43 44 croak "POE::Kernel expects its arguments in a hash ref" 45 if ($args && ref($args) ne 'HASH'); 46 47 { 48 no strict 'refs'; 49 *{ $package . '::poe_kernel' } = \$poe_kernel; 50 *{ $package . '::poe_main_window' } = \$poe_main_window; 51 } 52 53 # Extract the import arguments we're interested in here. 54 55 my $loop = delete $args->{loop} || $ENV{POE_EVENT_LOOP}; 56 57 # Don't accept unknown/mistyped arguments. 58 59 my @unknown = sort keys %$args; 60 croak "Unknown POE::Kernel import arguments: @unknown" if @unknown; 61 62 # Now do things with them. 63 64 unless (UNIVERSAL::can('POE::Kernel', 'poe_kernel_loop')) { 65 if (defined $loop) { 66 $loop =~ s/^(POE::)?(XS::)?(Loop::)?//; 67 if (defined $2) { 68 $loop = "POE::XS::Loop::$loop"; 69 } 70 else { 71 $loop = "POE::Loop::$loop"; 72 } 73 } 74 _test_loop($loop); 75 # Bootstrap the kernel. This is inherited from a time when multiple 76 # kernels could be present in the same Perl process. 77 POE::Kernel->new() if UNIVERSAL::can('POE::Kernel', 'poe_kernel_loop'); 78 } 79} 80 81#------------------------------------------------------------------------------ 82# Perform some optional setup. 83 84BEGIN { 85 local $SIG{'__DIE__'} = 'DEFAULT'; 86 87 { 88 no strict 'refs'; 89 if ($^O eq 'MSWin32') { 90 *{ __PACKAGE__ . '::RUNNING_IN_HELL' } = sub { 1 }; 91 } else { 92 *{ __PACKAGE__ . '::RUNNING_IN_HELL' } = sub { 0 }; 93 } 94 } 95} 96 97BEGIN { 98 # The entire BEGIN block is a no-strict-refs zone. 99 100 no strict 'refs'; 101 102 # Set up a constant that lets the user deactivate automatic 103 # exception handling. 104 105 unless (defined &CATCH_EXCEPTIONS) { 106 my $catch_exceptions = ( 107 (exists $ENV{POE_CATCH_EXCEPTIONS}) 108 ? $ENV{POE_CATCH_EXCEPTIONS} 109 : 1 110 ); 111 112 if ($catch_exceptions) { 113 *CATCH_EXCEPTIONS = sub () { 1 }; 114 } 115 else { 116 *CATCH_EXCEPTIONS = sub () { 0 }; 117 } 118 } 119 120 unless (defined &CHILD_POLLING_INTERVAL) { 121 # That's one second, not a true value. 122 *CHILD_POLLING_INTERVAL = sub () { 1 }; 123 } 124 125 unless (defined &USE_SIGCHLD) { 126 # Perl >= 5.7.3 has safe signals support 127 # perlipc.pod#Deferred_Signals_(Safe_Signals) 128 # We decided to target 5.8.1 just to be safe :) 129 if ( $] >= 5.008001 and not RUNNING_IN_HELL ) { 130 *USE_SIGCHLD = sub () { 1 }; 131 } else { 132 *USE_SIGCHLD = sub () { 0 }; 133 } 134 } 135 136 unless (defined &USE_SIGNAL_PIPE) { 137 my $use_signal_pipe; 138 if ( exists $ENV{POE_USE_SIGNAL_PIPE} ) { 139 $use_signal_pipe = $ENV{POE_USE_SIGNAL_PIPE}; 140 } 141 142 if (RUNNING_IN_HELL) { 143 if ($use_signal_pipe) { 144 _warn( 145 "Sorry, disabling USE_SIGNAL_PIPE on $^O.\n", 146 "Programs are reported to hang when it's enabled.\n", 147 ); 148 } 149 150 # Must be defined to supersede the default. 151 $use_signal_pipe = 0; 152 } 153 154 if ($use_signal_pipe or not defined $use_signal_pipe) { 155 *USE_SIGNAL_PIPE = sub () { 1 }; 156 } 157 else { 158 *USE_SIGNAL_PIPE = sub () { 0 }; 159 } 160 } 161} 162 163#============================================================================== 164# Globals, or at least package-scoped things. Data structures were 165# moved into lexicals in 0.1201. 166 167# A reference to the currently active session. Used throughout the 168# functions that act on the current session. 169my $kr_active_session; 170my $kr_active_event; 171my $kr_active_event_type; 172 173# Needs to be lexical so that POE::Resource::Events can see it 174# change. TODO - Something better? Maybe we call a method in 175# POE::Resource::Events to trigger the exception there? 176use vars qw($kr_exception); 177 178# The Kernel's master queue. 179my $kr_queue; 180 181# The current PID, to detect when it changes 182my $kr_pid; 183 184# Filehandle activity modes. They are often used as list indexes. 185sub MODE_RD () { 0 } # read 186sub MODE_WR () { 1 } # write 187sub MODE_EX () { 2 } # exception/expedite 188 189#------------------------------------------------------------------------------ 190# Kernel structure. This is the root of a large data tree. Dumping 191# $poe_kernel with Data::Dumper or something will show most of the 192# data that POE keeps track of. The exceptions to this are private 193# storage in some of the leaf objects, such as POE::Wheel. All its 194# members are described in detail further on. 195 196my $kr_id_seq = 0; 197 198sub KR_SESSIONS () { 0 } # [ \%kr_sessions, 199sub KR_FILENOS () { 1 } # \%kr_filenos, 200sub KR_SIGNALS () { 2 } # \%kr_signals, 201sub KR_ALIASES () { 3 } # \%kr_aliases, 202sub KR_ACTIVE_SESSION () { 4 } # \$kr_active_session, 203sub KR_QUEUE () { 5 } # \$kr_queue, 204sub KR_ID () { 6 } # $unique_kernel_id, 205sub KR_SESSION_IDS () { 7 } # \%kr_session_ids, 206sub KR_SID_SEQ () { 8 } # \$kr_sid_seq, 207sub KR_EXTRA_REFS () { 9 } # \$kr_extra_refs, 208sub KR_SIZE () { 10 } # XXX UNUSED ??? 209sub KR_RUN () { 11 } # \$kr_run_warning 210sub KR_ACTIVE_EVENT () { 12 } # \$kr_active_event 211sub KR_PIDS () { 13 } # \%kr_pids_to_events 212sub KR_ACTIVE_EVENT_TYPE () { 14 } # \$kr_active_event_type 213 # ] 214 215# This flag indicates that POE::Kernel's run() method was called. 216# It's used to warn about forgetting $poe_kernel->run(). 217 218sub KR_RUN_CALLED () { 0x01 } # $kernel->run() called 219sub KR_RUN_SESSION () { 0x02 } # sessions created 220sub KR_RUN_DONE () { 0x04 } # run returned 221my $kr_run_warning = 0; 222 223#------------------------------------------------------------------------------ 224# Events themselves. 225 226sub EV_SESSION () { 0 } # [ $destination_session, 227sub EV_SOURCE () { 1 } # $sender_session, 228sub EV_NAME () { 2 } # $event_name, 229sub EV_TYPE () { 3 } # $event_type, 230sub EV_ARGS () { 4 } # \@event_parameters_arg0_etc, 231 # 232 # (These fields go towards the end 233 # because they are optional in some 234 # cases. TODO: Is this still true?) 235 # 236sub EV_OWNER_FILE () { 5 } # $caller_filename_where_enqueued, 237sub EV_OWNER_LINE () { 6 } # $caller_line_where_enqueued, 238sub EV_FROMSTATE () { 7 } # $fromstate 239sub EV_SEQ () { 8 } # Maintained by POE::Queue (unique event ID) 240sub EV_WALLTIME () { 9 } # Walltime when event was created (for alarms) 241sub EV_DELTA () { 10 } # Seconds past walltime for event (for alarms) 242 # ] 243 244# These are the names of POE's internal events. They're in constants 245# so we don't mistype them again. 246 247sub EN_CHILD () { '_child' } 248sub EN_GC () { '_garbage_collect' } 249sub EN_PARENT () { '_parent' } 250sub EN_SCPOLL () { '_sigchld_poll' } 251sub EN_SIGNAL () { '_signal' } 252sub EN_START () { '_start' } 253sub EN_STOP () { '_stop' } 254 255# These are POE's event classes (types). They often shadow the event 256# names themselves, but they can encompass a large group of events. 257# For example, ET_ALARM describes anything enqueued as by an alarm 258# call. Types are preferred over names because bitmask tests are 259# faster than string equality tests. 260 261sub ET_POST () { 0x0001 } # User events (posted, yielded). 262sub ET_CALL () { 0x0002 } # User events that weren't enqueued. 263sub ET_START () { 0x0004 } # _start 264sub ET_STOP () { 0x0008 } # _stop 265sub ET_SIGNAL () { 0x0010 } # _signal 266sub ET_GC () { 0x0020 } # _garbage_collect 267sub ET_PARENT () { 0x0040 } # _parent 268sub ET_CHILD () { 0x0080 } # _child 269sub ET_SCPOLL () { 0x0100 } # _sigchild_poll 270sub ET_ALARM () { 0x0200 } # Alarm events. 271sub ET_SELECT () { 0x0400 } # File activity events. 272sub ET_SIGCLD () { 0x0800 } # sig_child() events. 273sub ET_SIGDIE () { 0x1000 } # SIGDIE exception events. 274 275# A mask for all events generated by/for users. 276sub ET_MASK_USER () { ~(ET_GC | ET_SCPOLL) } 277 278# A mask for all events that are delayed by a dispatch time. 279sub ET_MASK_DELAYED () { ET_ALARM | ET_SCPOLL } 280 281# Temporary signal subtypes, used during signal dispatch semantics 282# deprecation and reformation. 283 284sub ET_SIGNAL_RECURSIVE () { 0x2000 } # Explicitly requested signal. 285 286# A hash of reserved names. It's used to test whether someone is 287# trying to use an internal event directly. 288 289my %poes_own_events = ( 290 +EN_CHILD => 1, 291 +EN_GC => 1, 292 +EN_PARENT => 1, 293 +EN_SCPOLL => 1, 294 +EN_SIGNAL => 1, 295 +EN_START => 1, 296 +EN_STOP => 1, 297 +EN_STAT => 1, 298); 299 300# These are ways a child may come or go. 301# TODO - It would be useful to split 'lose' into two types. One to 302# indicate that the child has stopped, and one to indicate that it was 303# given away. 304 305sub CHILD_GAIN () { 'gain' } # The session was inherited from another. 306sub CHILD_LOSE () { 'lose' } # The session is no longer this one's child. 307sub CHILD_CREATE () { 'create' } # The session was created as a child of this. 308 309# Argument offsets for different types of internally generated events. 310# TODO Exporting (EXPORT_OK) these would let people stop depending on 311# positions for them. 312 313sub EA_SEL_HANDLE () { 0 } 314sub EA_SEL_MODE () { 1 } 315sub EA_SEL_ARGS () { 2 } 316 317#------------------------------------------------------------------------------ 318# Debugging and configuration constants. 319 320# Shorthand for defining a trace constant. 321sub _define_trace { 322 no strict 'refs'; 323 foreach my $name (@_) { 324 next if defined *{"TRACE_$name"}{CODE}; 325 my $trace_value = &TRACE_DEFAULT; 326 my $trace_name = "TRACE_$name"; 327 *$trace_name = sub () { $trace_value }; 328 } 329} 330 331# Debugging flags for subsystems. They're done as double evals here 332# so that someone may define them before using POE::Kernel (or POE), 333# and the pre-defined value will take precedence over the defaults 334# here. 335 336my $trace_file_handle; 337 338BEGIN { 339 # Shorthand for defining an assert constant. 340 sub _define_assert { 341 no strict 'refs'; 342 foreach my $name (@_) { 343 next if defined *{"ASSERT_$name"}{CODE}; 344 my $assert_value = &ASSERT_DEFAULT; 345 my $assert_name = "ASSERT_$name"; 346 *$assert_name = sub () { $assert_value }; 347 } 348 } 349 350 # Assimilate POE_TRACE_* and POE_ASSERT_* environment variables. 351 # Environment variables override everything else. 352 while (my ($var, $val) = each %ENV) { 353 next unless $var =~ /^POE_([A-Z_]+)$/; 354 355 my $const = $1; 356 357 next unless $const =~ /^(?:TRACE|ASSERT)_/ or do { no strict 'refs'; defined &$const }; 358 359 # Copy so we don't hurt our environment. 360 my $value = $val; 361 ($value) = ($value =~ /^([-\@\w.]+)$/); # Untaint per rt.cpan.org 81550 362 $value =~ tr['"][]d; 363 $value = 0 + $value if $value =~ /^\s*-?\d+(?:\.\d+)?\s*$/; 364 365 no strict 'refs'; 366 local $^W = 0; 367 local $SIG{__WARN__} = sub { }; # redefine 368 my $tmp = $value; 369 *$const = sub () { $tmp }; 370 } 371 372 # TRACE_FILENAME is special. 373 { 374 no strict 'refs'; 375 my $trace_filename = TRACE_FILENAME() if defined &TRACE_FILENAME; 376 if (defined $trace_filename) { 377 open $trace_file_handle, ">$trace_filename" 378 or die "can't open trace file `$trace_filename': $!"; 379 CORE::select((CORE::select($trace_file_handle), $| = 1)[0]); 380 } 381 } 382 # TRACE_DEFAULT changes the default value for other TRACE_* 383 # constants. Since define_trace() uses TRACE_DEFAULT internally, it 384 # can't be used to define TRACE_DEFAULT itself. 385 386 defined &TRACE_DEFAULT or *TRACE_DEFAULT = sub () { 0 }; 387 388 _define_trace qw( 389 EVENTS FILES PROFILE REFCNT RETVALS SESSIONS SIGNALS STATISTICS 390 ); 391 392 # See the notes for TRACE_DEFAULT, except read ASSERT and assert 393 # where you see TRACE and trace. 394 395 defined &ASSERT_DEFAULT or *ASSERT_DEFAULT = sub () { 0 }; 396 397 _define_assert qw(DATA EVENTS FILES RETVALS USAGE); 398} 399 400# An "idle" POE::Kernel may still have events enqueued. These events 401# regulate polling for signals, profiling, and perhaps other aspects of 402# POE::Kernel's internal workings. 403# 404# XXX - There must be a better mechanism. 405# 406my $idle_queue_size; 407 408sub _idle_queue_grow { $idle_queue_size++; } 409sub _idle_queue_shrink { $idle_queue_size--; } 410sub _idle_queue_size { $idle_queue_size; } 411sub _idle_queue_reset { $idle_queue_size = 0; } 412 413#------------------------------------------------------------------------------ 414# Helpers to carp, croak, confess, cluck, warn and die with whatever 415# trace file we're using today. _trap is reserved for internal 416# errors. 417 418sub _trap { 419 local $Carp::CarpLevel = $Carp::CarpLevel + 1; 420 local *STDERR = $trace_file_handle || *STDERR; 421 422 confess( 423 "=== $$ === Please address any warnings or errors above this message,\n", 424 "=== $$ === and try again. If there are no previous messages, or they\n", 425 "=== $$ === are from within POE, then please mail them along with the\n", 426 "=== $$ === following information to bug-POE\@rt.cpan.org:\n", 427 "---\n@_\n-----\n" 428 ); 429} 430 431sub _croak { 432 local $Carp::CarpLevel = $Carp::CarpLevel + 1; 433 local *STDERR = $trace_file_handle || *STDERR; 434 my $message = join("", @_); 435 $message =~ s/^/=== $$ === /mg; 436 croak $message; 437} 438 439sub _confess { 440 local $Carp::CarpLevel = $Carp::CarpLevel + 1; 441 local *STDERR = $trace_file_handle || *STDERR; 442 my $message = join("", @_); 443 $message =~ s/^/=== $$ === /mg; 444 confess $message; 445} 446 447sub _cluck { 448 local $Carp::CarpLevel = $Carp::CarpLevel + 1; 449 local *STDERR = $trace_file_handle || *STDERR; 450 my $message = join("", @_); 451 $message =~ s/^/=== $$ === /mg; 452 cluck $message; 453} 454 455sub _carp { 456 local $Carp::CarpLevel = $Carp::CarpLevel + 1; 457 local *STDERR = $trace_file_handle || *STDERR; 458 my $message = join("", @_); 459 $message =~ s/^/=== $$ === /mg; 460 carp $message; 461} 462 463sub _warn { 464 my ($package, $file, $line) = caller(); 465 my $message = join("", @_); 466 $message .= " at $file line $line\n" unless $message =~ /\n$/; 467 $message =~ s/^/=== $$ === /mg; 468 warn $message; 469} 470 471sub _die { 472 my ($package, $file, $line) = caller(); 473 my $message = join("", @_); 474 $message .= " at $file line $line\n" unless $message =~ /\n$/; 475 $message =~ s/^/=== $$ === /mg; 476 local *STDERR = $trace_file_handle || *STDERR; 477 die $message; 478} 479 480#------------------------------------------------------------------------------ 481# Adapt POE::Kernel's personality to whichever event loop is present. 482 483my @has_poe_loop; 484sub _find_loop { 485 my ($mod) = @_; 486 487 # Turns O(M*N) into O(M+N). I've seen the old way take over 30 488 # seconds according to Devel::NYTProf, with egregiously long @INCs. 489 unless (@has_poe_loop) { 490 @has_poe_loop = ( 491 grep { (-d "$_/POE/Loop") || (-d "$_/POE/XS/Loop") } 492 @INC 493 ); 494 } 495 496 foreach my $dir (@has_poe_loop) { 497 return 1 if (-r "$dir/$mod"); 498 } 499 500 return 0; 501} 502 503sub _load_loop { 504 my $loop = shift; 505 506 *poe_kernel_loop = sub { return "$loop" }; 507 508 # Modules can die with "not really dying" if they've loaded 509 # something else. This exception prevents the rest of the 510 # originally used module from being parsed, so the module it's 511 # handed off to takes over. 512 eval "require $loop"; 513 if ($@ and $@ !~ /not really dying/) { 514 die( 515 "*\n", 516 "* POE can't use $loop:\n", 517 "* $@\n", 518 "*\n", 519 ); 520 } 521} 522 523sub _test_loop { 524 my $used_first = shift; 525 local $SIG{__DIE__}; 526 527 # First see if someone wants to load a POE::Loop or XS version 528 # explicitly. 529 if (defined $used_first) { 530 _load_loop($used_first); 531 return; 532 } 533 534 foreach my $file (keys %INC) { 535 next if (substr ($file, -3) ne '.pm'); 536 my @split_dirs = File::Spec->splitdir($file); 537 538 # Create a module name by replacing the path separators with 539 # underscores and removing ".pm" 540 my $module = join("_", @split_dirs); 541 substr($module, -3) = ""; 542 543 # Skip the module name if it isn't legal. 544 next if $module =~ /[^\w\.]/; 545 546 # Try for the XS version first. If it fails, try the plain 547 # version. If that fails, we're up a creek. 548 $module = "POE/XS/Loop/$module.pm"; 549 unless (_find_loop($module)) { 550 $module =~ s|XS/||; 551 next unless (_find_loop($module)); 552 } 553 554 if (defined $used_first and $used_first ne $module) { 555 die( 556 "*\n", 557 "* POE can't use multiple event loops at once.\n", 558 "* You used $used_first and $module.\n", 559 "* Specify the loop you want as an argument to POE\n", 560 "* use POE qw(Loop::Select);\n", 561 "* or;\n", 562 "* use POE::Kernel { loop => 'Select' };\n", 563 "*\n", 564 ); 565 } 566 567 $used_first = $module; 568 } 569 570 # No loop found. Default to our internal select() loop. 571 unless (defined $used_first) { 572 $used_first = "POE/XS/Loop/Select.pm"; 573 unless (_find_loop($used_first)) { 574 $used_first =~ s/XS\///; 575 } 576 } 577 578 substr($used_first, -3) = ""; 579 $used_first =~ s|/|::|g; 580 _load_loop($used_first); 581} 582 583#------------------------------------------------------------------------------ 584# Include resource modules here. Later, when we have the option of XS 585# versions, we'll adapt this to include them if they're available. 586 587use POE::Resources; 588 589############################################################################### 590# Helpers. 591 592### Resolve $whatever into a session reference, trying every method we 593### can until something succeeds. 594 595sub _resolve_session { 596 my ($self, $whatever) = @_; 597 my $session; 598 599 # Resolve against sessions. 600 $session = $self->_data_ses_resolve($whatever); 601 return $session if defined $session; 602 603 # Resolve against IDs. 604 $session = $self->_data_sid_resolve($whatever); 605 return $session if defined $session; 606 607 # Resolve against aliases. 608 $session = $self->_data_alias_resolve($whatever); 609 return $session if defined $session; 610 611 # Resolve against the Kernel itself. Use "eq" instead of "==" here 612 # because $whatever is often a string. 613 return $whatever if $whatever eq $self; 614 615 # We don't know what it is. 616 return undef; 617} 618 619### Test whether POE has become idle. 620 621sub _test_if_kernel_is_idle { 622 my $self = shift; 623 624 if (TRACE_REFCNT) { 625 _warn( 626 "<rc> ,----- Kernel Activity -----\n", 627 "<rc> | Events : ", $kr_queue->get_item_count(), 628 " (vs. idle size = ", $idle_queue_size, ")\n", 629 "<rc> | Files : ", $self->_data_handle_count(), "\n", 630 "<rc> | Extra : ", $self->_data_extref_count(), "\n", 631 "<rc> | Procs : ", $self->_data_sig_kernel_awaits_pids(), "\n", 632 "<rc> | Sess : ", $self->_data_ses_count(), "\n", 633 "<rc> `---------------------------\n", 634 "<rc> ..." 635 ); 636 } 637 638 if( ASSERT_DATA ) { 639 if( $kr_pid != $$ ) { 640 _trap( 641 "New process detected. " . 642 "You must call ->has_forked() in the child process." 643 ); 644 } 645 } 646 647 # Not yet idle, or SO idle that there's nothing to receive the 648 # event. Try to order these from most to least likely to be true so 649 # that the tests short-circuit quickly. 650 651 return if ( 652 $kr_queue->get_item_count() > $idle_queue_size or 653 $self->_data_handle_count() or 654 $self->_data_extref_count() or 655 $self->_data_sig_kernel_awaits_pids() or 656 !$self->_data_ses_count() 657 ); 658 659 $self->_data_ev_enqueue( 660 $self, $self, EN_SIGNAL, ET_SIGNAL, [ 'IDLE' ], 661 __FILE__, __LINE__, undef 662 ); 663} 664 665### Explain why a session could not be resolved. 666 667sub _explain_resolve_failure { 668 my ($self, $whatever, $nonfatal) = @_; 669 local $Carp::CarpLevel = 2; 670 671 if (ASSERT_DATA and !$nonfatal) { 672 _trap "<dt> Cannot resolve ``$whatever'' into a session reference"; 673 } 674 675 $! = ESRCH; 676 TRACE_RETVALS and _carp "<rv> session not resolved: $!"; 677 ASSERT_RETVALS and _carp "<rv> session not resolved: $!"; 678} 679 680### Explain why a function is returning unsuccessfully. 681 682sub _explain_return { 683 my ($self, $message) = @_; 684 local $Carp::CarpLevel = 2; 685 686 ASSERT_RETVALS and _confess "<rv> $message"; 687 TRACE_RETVALS and _carp "<rv> $message"; 688} 689 690### Explain how the user made a mistake calling a function. 691 692sub _explain_usage { 693 my ($self, $message) = @_; 694 local $Carp::CarpLevel = 2; 695 696 ASSERT_USAGE and _confess "<us> $message"; 697 ASSERT_RETVALS and _confess "<rv> $message"; 698 TRACE_RETVALS and _carp "<rv> $message"; 699} 700 701#============================================================================== 702# SIGNALS 703#============================================================================== 704 705#------------------------------------------------------------------------------ 706# Register or remove signals. 707 708# Public interface for adding or removing signal handlers. 709 710sub sig { 711 my ($self, $signal, $event_name, @args) = ($poe_kernel, @_[1..$#_]); 712 713 if (ASSERT_USAGE) { 714 _confess "<us> must call sig() from a running session" 715 if $kr_active_session == $self; 716 _confess "<us> undefined signal in sig()" unless defined $signal; 717 _carp( 718 "<us> The '$event_name' event is one of POE's own. Its " . 719 "effect cannot be achieved assigning it to a signal" 720 ) if defined($event_name) and exists($poes_own_events{$event_name}); 721 }; 722 723 if (defined $event_name) { 724 $self->_data_sig_add($kr_active_session, $signal, $event_name, \@args); 725 } 726 else { 727 $self->_data_sig_remove($kr_active_session->ID, $signal); 728 } 729} 730 731# Public interface for posting signal events. 732# TODO - Like post(), signal() should return 733 734sub signal { 735 my ($self, $dest_session, $signal, @etc) = ($poe_kernel, @_[1..$#_]); 736 737 if (ASSERT_USAGE) { 738 _confess "<us> undefined destination in signal()" 739 unless defined $dest_session; 740 _confess "<us> undefined signal in signal()" unless defined $signal; 741 }; 742 743 my $session = $self->_resolve_session($dest_session); 744 unless (defined $session) { 745 $self->_explain_resolve_failure($dest_session); 746 return; 747 } 748 749 $self->_data_ev_enqueue( 750 $session, $kr_active_session, 751 EN_SIGNAL, ET_SIGNAL, [ $signal, @etc ], 752 (caller)[1,2], $kr_active_event 753 ); 754 return 1; 755} 756 757# Public interface for flagging signals as handled. This will replace 758# the handlers' return values as an implicit flag. Returns undef so 759# it may be used as the last function in an event handler. 760 761sub sig_handled { 762 my $self = $poe_kernel; 763 $self->_data_sig_handled(); 764 765 if ($kr_active_event eq EN_SIGNAL) { 766 _die( 767 ",----- DEPRECATION ERROR -----\n", 768 "| ", $self->_data_alias_loggable($kr_active_session->ID), ":\n", 769 "| handled a _signal event. You must register a handler with sig().\n", 770 "`-----------------------------\n", 771 ); 772 } 773} 774 775# Attach a window or widget's destroy/closure to the UIDESTROY signal. 776 777sub signal_ui_destroy { 778 my ($self, $window) = @_; 779 $self->loop_attach_uidestroy($window); 780} 781 782# Handle child PIDs being reaped. Added 2006-09-15. 783 784sub sig_child { 785 my ($self, $pid, $event_name, @args) = ($poe_kernel, @_[1..$#_]); 786 787 if (ASSERT_USAGE) { 788 _confess "<us> must call sig_chld() from a running session" 789 if $kr_active_session == $self; 790 _confess "<us> undefined process ID in sig_chld()" unless defined $pid; 791 _carp( 792 "<us> The '$event_name' event is one of POE's own. Its " . 793 "effect cannot be achieved assigning it to a signal" 794 ) if defined($event_name) and exists($poes_own_events{$event_name}); 795 }; 796 797 if (defined $event_name) { 798 $self->_data_sig_pid_watch($kr_active_session, $pid, $event_name, \@args); 799 } 800 elsif ($self->_data_sig_pids_is_ses_watching($kr_active_session->ID, $pid)) { 801 $self->_data_sig_pid_ignore($kr_active_session->ID, $pid); 802 } 803} 804 805#============================================================================== 806# KERNEL 807#============================================================================== 808 809sub new { 810 my $type = shift; 811 812 # Prevent multiple instances, no matter how many times it's called. 813 # This is a backward-compatibility enhancement for programs that 814 # have used versions prior to 0.06. It also provides a convenient 815 # single entry point into the entirety of POE's state: point a 816 # Dumper module at it, and you'll see a hideous tree of knowledge. 817 # Be careful, though. Its apples bite back. 818 unless (defined $poe_kernel) { 819 820 # Create our master queue. 821 $kr_queue = $queue_class->new(); 822 823 # Remember the PID 824 $kr_pid = $$; 825 826 # TODO - Should KR_ACTIVE_SESSIONS and KR_ACTIVE_EVENT be handled 827 # by POE::Resource::Sessions? 828 # TODO - Should the subsystems be split off into separate real 829 # objects, such as KR_QUEUE is? 830 831 my $self = $poe_kernel = bless [ 832 undef, # KR_SESSIONS - from POE::Resource::Sessions 833 undef, # KR_FILENOS - from POE::Resource::FileHandles 834 undef, # KR_SIGNALS - from POE::Resource::Signals 835 undef, # KR_ALIASES - from POE::Resource::Aliases 836 \$kr_active_session, # KR_ACTIVE_SESSION 837 $kr_queue, # KR_QUEUE - reference to an object 838 undef, # KR_ID 839 undef, # KR_SESSION_IDS - from POE::Resource::SIDS 840 undef, # KR_SID_SEQ - from POE::Resource::SIDS 841 undef, # KR_EXTRA_REFS 842 undef, # KR_SIZE 843 \$kr_run_warning, # KR_RUN 844 \$kr_active_event, # KR_ACTIVE_EVENT 845 undef, # KR_PIDS 846 \$kr_active_event_type, # KR_ACTIVE_EVENT_TYPE 847 ], $type; 848 849 POE::Resources->load(); 850 851 $self->_recalc_id(); 852 $self->_data_sid_set($self->[KR_ID], $self); 853 854 # Initialize subsystems. The order is important. 855 856 # We need events before sessions, and the kernel's session before 857 # it can start polling for signals. 858 $self->_data_ev_initialize($kr_queue); 859 $self->_initialize_kernel_session(); 860 $self->_data_sig_initialize(); 861 $self->_data_alias_initialize(); 862 863 # These other subsystems don't have strange interactions. 864 $self->_data_handle_initialize($kr_queue); 865 866 _idle_queue_reset(); 867 } 868 869 # Return the global instance. 870 $poe_kernel; 871} 872 873sub CLONE { 874 _data_ses_clone(); 875} 876 877#------------------------------------------------------------------------------ 878# Send an event to a session right now. Used by _disp_select to 879# expedite select() events, and used by run() to deliver posted events 880# from the queue. 881 882# Dispatch an event to its session. A lot of work goes on here. 883 884sub _dummy_sigdie_handler { 1 } 885 886sub _dispatch_signal_event { 887 my ( 888 $self, 889 $session, $source_session, $event, $type, $etc, 890 $file, $line, $fromstate, $priority, $seq 891 ) = @_; 892 893 # TODO - Regrettably, duplicate checking code in: 894 # _dispatch_signal_event(), _dispatch_event(). 895 896 if (ASSERT_EVENTS) { 897 _confess "<ev> undefined dest session" unless defined $session; 898 _confess "<ev> undefined source session" unless defined $source_session; 899 }; 900 901 if (TRACE_EVENTS) { 902 my $log_session = $session; 903 $log_session = $self->_data_alias_loggable($session->ID) unless ( 904 $type & ET_START 905 ); 906 my $string_etc = join(" ", map { defined() ? $_ : "(undef)" } @$etc); 907 _warn( 908 "<ev> Dispatching event $seq ``$event'' ($string_etc) from ", 909 $self->_data_alias_loggable($source_session->ID), " to $log_session" 910 ); 911 } 912 913 my $signal = $etc->[0]; 914 915 if (TRACE_SIGNALS) { 916 _warn( 917 "<sg> dispatching ET_SIGNAL ($signal) to ", 918 $self->_data_alias_loggable($session->ID) 919 ); 920 } 921 922 # Step 1a: Reset the handled-signal flags. 923 924 local @POE::Kernel::kr_signaled_sessions; 925 local $POE::Kernel::kr_signal_total_handled; 926 local $POE::Kernel::kr_signal_type; 927 928 $self->_data_sig_reset_handled($signal); 929 930 # Step 1b: Collect a list of sessions to receive the signal. 931 932 my @touched_sessions = ($session); 933 my $touched_index = 0; 934 while ($touched_index < @touched_sessions) { 935 my $next_target = $touched_sessions[$touched_index]->ID; 936 push @touched_sessions, $self->_data_ses_get_children($next_target); 937 $touched_index++; 938 } 939 940 # Step 1c: The DIE signal propagates up through parents, too. 941 942 if ($signal eq "DIE") { 943 my $next_target = $self->_data_ses_get_parent($session->ID); 944 while (defined($next_target) and $next_target != $self) { 945 unshift @touched_sessions, $next_target; 946 $next_target = $self->_data_ses_get_parent($next_target->ID); 947 } 948 } 949 950 # Step 2: Propagate the signal to the explicit watchers in the 951 # child tree. Ensure the full tree is touched regardless 952 # whether there are explicit watchers. 953 954 if ($self->_data_sig_explicitly_watched($signal)) { 955 my %signal_watchers = $self->_data_sig_watchers($signal); 956 957 $touched_index = @touched_sessions; 958 while ($touched_index--) { 959 my $target_session = $touched_sessions[$touched_index]; 960 $self->_data_sig_touched_session($target_session); 961 962 my $target_sid = $target_session->ID; 963 next unless exists $signal_watchers{$target_sid}; 964 my ($target_event, $target_etc) = @{$signal_watchers{$target_sid}}; 965 966 if (TRACE_SIGNALS) { 967 _warn( 968 "<sg> propagating explicit signal $target_event ($signal) ", 969 "(@$target_etc) to ", $self->_data_alias_loggable($target_sid) 970 ); 971 } 972 973 # ET_SIGNAL_RECURSIVE is used here to avoid repropagating 974 # the signal ad nauseam. 975 $self->_dispatch_event( 976 $target_session, $self, 977 $target_event, ET_SIGNAL_RECURSIVE | $type, [ @$etc, @$target_etc ], 978 $file, $line, $fromstate, monotime(), -__LINE__ 979 ); 980 } 981 } 982 else { 983 $touched_index = @touched_sessions; 984 while ($touched_index--) { 985 $self->_data_sig_touched_session($touched_sessions[$touched_index]); 986 } 987 } 988 989 # Step 3: Check to see if the signal was handled. 990 991 $self->_data_sig_free_terminated_sessions(); 992 993 # If the signal was SIGDIE, then propagate the exception. 994 995 my $handled_session_count = (_data_sig_handled_status())[0]; 996 if ($signal eq "DIE" and !$handled_session_count) { 997 $kr_exception = $etc->[1]{error_str} . ( 998 (defined $kr_exception) 999 ? "Additional error thrown in handler for previous error:\n$kr_exception" 1000 : '' 1001 ); 1002 } 1003 1004 # Signal completely dispatched. Thanks for flying! 1005 return; 1006} 1007 1008sub _dispatch_event { 1009 my ( 1010 $self, 1011 $session, $source_session, $event, $type, $etc, 1012 $file, $line, $fromstate, $priority, $seq 1013 ) = @_; 1014 1015 if (ASSERT_EVENTS) { 1016 _confess "<ev> undefined dest session" unless defined $session; 1017 _confess "<ev> undefined source session" unless defined $source_session; 1018 }; 1019 1020 if (TRACE_EVENTS) { 1021 my $log_session = $session; 1022 $log_session = $self->_data_alias_loggable($session->ID) unless ( 1023 $type & ET_START 1024 ); 1025 my $string_etc = join(" ", map { defined() ? $_ : "(undef)" } @$etc); 1026 _warn( 1027 "<ev> Dispatching event $seq ``$event'' ($string_etc) from ", 1028 $self->_data_alias_loggable($source_session->ID), " to $log_session" 1029 ); 1030 } 1031 1032 ### Pre-dispatch processing. 1033 1034 # Some sessions don't do anything in _start and expect their 1035 # creators to provide a start-up event. This means we can't 1036 # &_collect_garbage at _start time. Instead, an ET_GC event is 1037 # posted as part of session allocation. Simply dispatching it 1038 # will trigger a GC sweep. 1039 1040 return 0 if $type & ET_GC; 1041 1042 # Preprocess signals. This is where _signal is translated into 1043 # its registered handler's event name, if there is one. 1044 1045 if (TRACE_EVENTS) { 1046 _warn( 1047 "<ev> dispatching event $seq ``$event'' to ", 1048 $self->_data_alias_loggable($session->ID) 1049 ); 1050 if ($event eq EN_SIGNAL) { 1051 _warn("<ev> signal($etc->[0])"); 1052 } 1053 } 1054 1055 # Prepare to call the appropriate handler. Push the current active 1056 # session on Perl's call stack. 1057 1058 my ($hold_active_session, $hold_active_event, $hold_active_event_type) = ( 1059 $kr_active_session, $kr_active_event, $kr_active_event_type 1060 ); 1061 ( 1062 $kr_active_session, $kr_active_event, $kr_active_event_type 1063 ) = ($session, $event, $type); 1064 1065 # We only care about the return value and calling context if it's 1066 # ET_CALL. 1067 1068 my $return; 1069 my $wantarray = wantarray(); 1070 1071 confess 'please report this stacktrace to bug-poe@rt.cpan.org' unless ( 1072 defined $session 1073 ); 1074 1075 # Quiet SIGDIE if it's DEFAULT. If it's something special, then 1076 # someone had better know what they're doing. 1077 # 'DEFAULT', undef and '' are all the same. 1078 1079 my $old_sig_die = $SIG{__DIE__}; 1080 $SIG{__DIE__} = \&_dummy_sigdie_handler if ( 1081 not defined $old_sig_die or $old_sig_die eq 'DEFAULT' or $old_sig_die eq '' 1082 ); 1083 1084 eval { 1085 if ($wantarray) { 1086 $return = [ 1087 $session->_invoke_state( 1088 $source_session, $event, $etc, $file, $line, $fromstate 1089 ) 1090 ]; 1091 } 1092 elsif (defined $wantarray) { 1093 $return = $session->_invoke_state( 1094 $source_session, $event, $etc, $file, $line, $fromstate 1095 ); 1096 } 1097 else { 1098 $session->_invoke_state( 1099 $source_session, $event, $etc, $file, $line, $fromstate 1100 ); 1101 } 1102 }; 1103 1104 # An exception happened? 1105 # It was intially thrown under the $SIG{__DIE__} conditions that the 1106 # user wanted. Any formatting, logging, etc. is already done. 1107 1108 if (ref($@) or $@ ne '') { 1109 if (CATCH_EXCEPTIONS) { 1110 if (TRACE_EVENTS) { 1111 _warn( 1112 "<ev> exception occurred in $event when invoked on ", 1113 $self->_data_alias_loggable($session->ID) 1114 ); 1115 } 1116 1117 # Exceptions in _stop are rethrown unconditionally. 1118 # We can't enqueue them--the session is about to go away. 1119 # Also if the active session has been forced back to $self via 1120 # POE::Kernel->stop(). 1121 if ($type & (ET_STOP | ET_SIGDIE) or $kr_active_session eq $self) { 1122 # Propagate the exception up to the safe rethrow point. 1123 $kr_exception = $@; 1124 } 1125 else { 1126 $self->_data_ev_enqueue( 1127 $session, $self, EN_SIGNAL, ET_SIGDIE, [ 1128 'DIE' => { 1129 source_session => $source_session, 1130 dest_session => $session, 1131 event => $event, 1132 file => $file, 1133 line => $line, 1134 from_state => $fromstate, 1135 error_str => $@, 1136 }, 1137 ], __FILE__, __LINE__, undef 1138 ); 1139 } 1140 } 1141 else { 1142 # Propagate the exception up to the safe rethrow point. 1143 $kr_exception = $@; 1144 } 1145 } 1146 1147 # Global $sig{__DIE__} changed? For shame! 1148 # TODO - This warning is only needed if a SIGDIE handler is active. 1149 # TODO - Likewise, setting a SIGDIE with a __DIE__ handler in play 1150 # will be tricky or impossible. There should be some message. 1151 1152 if ( 1153 (not defined $old_sig_die or $old_sig_die eq 'DEFAULT') and 1154 $SIG{__DIE__} ne \&_dummy_sigdie_handler 1155 ) { 1156 _warn( 1157 "<sg> Event handler redefined global __DIE__ signal handler.\n", 1158 "<sg> This may conflict with CATCH_EXCEPTIONS handling.\n", 1159 "<sg> If global redefinition is necessary, do it in global code.\n", 1160 ); 1161 1162 $SIG{__DIE__} = $old_sig_die; 1163 } 1164 1165 # Clear out the event arguments list, in case there are POE-ish 1166 # things in it. This allows them to destruct happily before we set 1167 # the current session back. 1168 1169 @$etc = ( ); 1170 1171 # Stringify the handler's return value if it belongs in the POE 1172 # namespace. $return's scope exists beyond the post-dispatch 1173 # processing, which includes POE's garbage collection. The scope 1174 # bleed was known to break determinism in surprising ways. 1175 1176 if (defined $return and substr(ref($return), 0, 5) eq 'POE::') { 1177 $return = "$return"; 1178 } 1179 1180 # Pop the active session and event, now that they're no longer 1181 # active. 1182 1183 ($kr_active_session, $kr_active_event, $kr_active_event_type) = ( 1184 $hold_active_session, $hold_active_event, $hold_active_event_type 1185 ); 1186 1187 if (TRACE_EVENTS) { 1188 my $string_ret = $return; 1189 $string_ret = "undef" unless defined $string_ret; 1190 _warn("<ev> event $seq ``$event'' returns ($string_ret)\n"); 1191 } 1192 1193 # Return doesn't matter unless ET_CALL, ET_START or ET_STOP. 1194 return unless $type & (ET_CALL | ET_START | ET_STOP); 1195 1196 # Return what the handler did. This is used for call(). 1197 return( $wantarray ? @$return : $return ); 1198} 1199 1200#------------------------------------------------------------------------------ 1201# POE's main loop! Now with Tk and Event support! 1202 1203# Do pre-run start-up. Initialize the event loop, and allocate a 1204# session structure to represent the Kernel. 1205 1206sub _initialize_kernel_session { 1207 my $self = shift; 1208 1209 $self->loop_initialize(); 1210 1211 $kr_exception = undef; 1212 $kr_active_session = $self; 1213 $self->_data_ses_allocate($self, $self->[KR_ID], undef); 1214} 1215 1216# Do post-run cleanup. 1217 1218sub _finalize_kernel { 1219 my $self = shift; 1220 1221 # Disable signal watching since there's now no place for them to go. 1222 foreach ($self->_data_sig_get_safe_signals()) { 1223 $self->loop_ignore_signal($_); 1224 } 1225 1226 # Remove the kernel session's signal watcher. 1227 $self->_data_sig_remove($self->ID, "IDLE"); 1228 1229 # The main loop is done, no matter which event library ran it. 1230 # sig before loop so that it clears the signal_pipe file handler 1231 $self->_data_sig_finalize(); 1232 $self->loop_finalize(); 1233 $self->_data_extref_finalize(); 1234 $self->_data_sid_finalize(); 1235 $self->_data_alias_finalize(); 1236 $self->_data_handle_finalize(); 1237 $self->_data_ev_finalize(); 1238 $self->_data_ses_finalize(); 1239} 1240 1241sub run_while { 1242 my ($self, $scalar_ref) = ($poe_kernel, @_[1..$#_]); 1243 1 while $$scalar_ref and $self->run_one_timeslice(); 1244} 1245 1246sub run_one_timeslice { 1247 my $self = $poe_kernel; 1248 1249 unless ($self->_data_ses_count()) { 1250 $self->_finalize_kernel(); 1251 $kr_run_warning |= KR_RUN_DONE; 1252 $kr_exception and $self->_rethrow_kr_exception(); 1253 return; 1254 } 1255 1256 $self->loop_do_timeslice(); 1257 $kr_exception and $self->_rethrow_kr_exception(); 1258 1259 return 1; 1260} 1261 1262sub run { 1263 # So run() can be called as a class method. 1264 POE::Kernel->new unless defined $poe_kernel; 1265 my $self = $poe_kernel; 1266 1267 # Flag that run() was called. 1268 $kr_run_warning |= KR_RUN_CALLED; 1269 1270 # TODO is this check expensive? ( do people run() more than 1 time? ) 1271 if( $kr_pid != $$ ) { 1272 if ( ASSERT_USAGE ) { 1273 _warn "Detected a fork, automatically calling ->has_forked()"; 1274 } 1275 $self->has_forked; 1276 } 1277 1278 # Don't run the loop if we have no sessions. 1279 # Loop::Event will blow up, so we're doing this sanity check. 1280 # It may never trigger, however: See rt.cpan.org 101227. 1281 if ( $self->_data_ses_count() == 0 ) { 1282 # Emit noise only if we are under debug mode 1283 if ( ASSERT_DATA ) { 1284 _warn("Not running the event loop because we have no sessions!\n"); 1285 } 1286 } else { 1287 # All signals must be explicitly watched now. We do it here because 1288 # it's too early in initialize_kernel_session. 1289 $self->_data_sig_add($self, "IDLE", EN_SIGNAL); 1290 1291 # Run the loop! 1292 $self->loop_run(); 1293 1294 # Cleanup 1295 $self->_finalize_kernel(); 1296 } 1297 1298 # Clean up afterwards. 1299 $kr_run_warning |= KR_RUN_DONE; 1300 1301 $kr_exception and $self->_rethrow_kr_exception(); 1302} 1303 1304sub _rethrow_kr_exception { 1305 my $self = shift; 1306 1307 # It's quite common to see people wrap POE::Kernel->run() in an eval 1308 # block and start things again if an exception is caught. 1309 # 1310 # This little lexical dance is actually important. It allows 1311 # $kr_exception to be cleared if the die() is caught. 1312 1313 my $exception = $kr_exception; 1314 $kr_exception = undef; 1315 1316 # The die is cast. 1317 die $exception; 1318} 1319 1320# Stops the kernel cold. XXX Experimental! 1321# No events happen as a result of this, all structures are cleaned up 1322# except the kernel's. Even the current session and POE::Kernel are 1323# cleaned up, which may introduce inconsistencies in the current 1324# session... as _dispatch_event() attempts to clean up for a defunct 1325# session. 1326 1327sub stop { 1328 # So stop() can be called as a class method. 1329 my $self = $poe_kernel; 1330 1331 # May be called when the kernel's already stopped. Avoid problems 1332 # trying to find child sessions when the kernel isn't registered. 1333 if ($self->_data_ses_exists($self->ID)) { 1334 my @children = ($self); 1335 foreach my $session (@children) { 1336 push @children, $self->_data_ses_get_children($session->ID); 1337 } 1338 1339 # Don't stop believin'. Nor the POE::Kernel singleton. 1340 shift @children; 1341 1342 # Walk backwards to avoid inconsistency errors. 1343 foreach my $session (reverse @children) { 1344 $self->_data_ses_stop($session->ID); 1345 } 1346 } 1347 1348 # Roll back whether sessions were started. 1349 $kr_run_warning &= ~KR_RUN_SESSION; 1350 1351 # So new sessions will not be child of the current defunct session. 1352 $kr_active_session = $self; 1353 1354 # The GC mark list may prevent sessions from DESTROYing. 1355 # Clean it up. 1356 $self->_data_ses_gc_sweep(); 1357 1358 # Running stop() is recommended in a POE::Wheel::Run coderef 1359 # Program, before setting up for the next POE::Kernel->run(). When 1360 # the PID has changed, imply _data_sig_has_forked() during stop(). 1361 1362 $poe_kernel->has_forked() if $kr_pid != $$; 1363 1364 # TODO - If we're polling for signals, then the reset gets it wrong. 1365 # The reset doesn't count sigchld polling. If we must put this 1366 # back, it MUST account for all internal events currently in play, 1367 # or the child process will stall if it reruns POE::Kernel's loop. 1368 #_idle_queue_reset(); 1369 1370 return; 1371} 1372 1373# Less invasive form of ->stop() + ->run() 1374sub has_forked { 1375 if( $kr_pid == $$ ) { 1376 if ( ASSERT_USAGE ) { 1377 _warn "You should only call ->has_forked() from the child process."; 1378 } 1379 return; 1380 } 1381 1382 # So has_forked() can be called as a class method. 1383 my $self = $poe_kernel; 1384 1385 $kr_pid = $$; 1386 $self->_recalc_id(); 1387 1388 # reset some stuff for the signals 1389 $poe_kernel->_data_sig_has_forked; 1390} 1391 1392#------------------------------------------------------------------------------ 1393 1394sub DESTROY { 1395 my $self = shift; 1396 1397 # Warn that a session never had the opportunity to run if one was 1398 # created but run() was never called. 1399 1400 unless ($kr_run_warning & KR_RUN_CALLED) { 1401 if ($kr_run_warning & KR_RUN_SESSION) { 1402 _warn( 1403 "Sessions were started, but POE::Kernel's run() method was never\n", 1404 "called to execute them. This usually happens because an error\n", 1405 "occurred before POE::Kernel->run() could be called. Please fix\n", 1406 "any errors above this notice, and be sure that POE::Kernel->run()\n", 1407 "is called. See documentation for POE::Kernel's run() method for\n", 1408 "another way to disable this warning.\n", 1409 ); 1410 } 1411 } 1412} 1413 1414#------------------------------------------------------------------------------ 1415# _invoke_state is what _dispatch_event calls to dispatch a transition 1416# event. This is the kernel's _invoke_state so it can receive events. 1417# These are mostly signals, which are propagated down in 1418# _dispatch_event. 1419 1420sub _invoke_state { 1421 my ($self, $source_session, $event, $etc) = @_; 1422 1423 # This is an event loop to poll for child processes without needing 1424 # to catch SIGCHLD. 1425 1426 if ($event eq EN_SCPOLL) { 1427 $self->_data_sig_handle_poll_event($etc->[0]); 1428 } 1429 1430 # A signal was posted. Because signals propagate depth-first, this 1431 # _invoke_state is called last in the dispatch. If the signal was 1432 # SIGIDLE, then post a SIGZOMBIE if the main queue is still idle. 1433 1434 elsif ($event eq EN_SIGNAL) { 1435 if ($etc->[0] eq 'IDLE') { 1436 unless ( 1437 $kr_queue->get_item_count() > $idle_queue_size or 1438 $self->_data_handle_count() 1439 ) { 1440 $self->_data_ev_enqueue( 1441 $self, $self, EN_SIGNAL, ET_SIGNAL, [ 'ZOMBIE' ], 1442 __FILE__, __LINE__, undef 1443 ); 1444 } 1445 } 1446 } 1447 1448 return 0; 1449} 1450 1451#============================================================================== 1452# SESSIONS 1453#============================================================================== 1454 1455# Dispatch _start to a session, allocating it in the kernel's data 1456# structures as a side effect. 1457 1458sub session_alloc { 1459 my ($self, $session, @args) = ($poe_kernel, @_[1..$#_]); 1460 1461 # If we already returned, then we must reinitialize. This is so 1462 # $poe_kernel->run() will work correctly more than once. 1463 if ($kr_run_warning & KR_RUN_DONE) { 1464 $kr_run_warning &= ~KR_RUN_DONE; 1465 $self->_initialize_kernel_session(); 1466 $self->_data_sig_initialize(); 1467 } 1468 1469 if (ASSERT_DATA) { 1470 if (defined $session->ID) { 1471 _trap( 1472 "<ss> ", $self->_data_alias_loggable($session->ID), 1473 " already allocated\a" 1474 ); 1475 } 1476 } 1477 1478 # Register that a session was created. 1479 $kr_run_warning |= KR_RUN_SESSION; 1480 1481 # Allocate the session's data structure. This must be done before 1482 # we dispatch anything regarding the new session. 1483 my $new_sid = $self->_data_sid_allocate(); 1484 $session->_set_id($new_sid); 1485 $self->_data_ses_allocate($session, $new_sid, $kr_active_session->ID); 1486 1487 my $loggable = $self->_data_alias_loggable($new_sid); 1488 1489 # Tell the new session that it has been created. Catch the _start 1490 # state's return value so we can pass it to the parent with the 1491 # _child create. 1492 # 1493 # TODO - Void the context if the parent has no _child handler? 1494 1495 my $return = $self->_dispatch_event( 1496 $session, $kr_active_session, 1497 EN_START, ET_START, \@args, 1498 __FILE__, __LINE__, undef, monotime(), -__LINE__ 1499 ); 1500 1501 unless($self->_data_ses_exists($new_sid)) { 1502 if(TRACE_SESSIONS) { 1503 _warn("<ss> ", $loggable, " disappeared during ", EN_START); 1504 } 1505 return $return; 1506 } 1507 1508 # If the child has not detached itself---that is, if its parent is 1509 # the currently active session---then notify the parent with a 1510 # _child create event. Otherwise skip it, since we'd otherwise 1511 # throw a create without a lose. 1512 $self->_dispatch_event( 1513 $self->_data_ses_get_parent($session->ID), $self, 1514 EN_CHILD, ET_CHILD, [ CHILD_CREATE, $session, $return ], 1515 __FILE__, __LINE__, undef, monotime(), -__LINE__ 1516 ); 1517 1518 unless ($self->_data_ses_exists($new_sid)) { 1519 if (TRACE_SESSIONS) { 1520 _warn("<ss> ", $loggable, " disappeared during ", EN_CHILD, " dispatch"); 1521 } 1522 return $return; 1523 } 1524 1525 # Enqueue a delayed garbage-collection event so the session has time 1526 # to do its thing before it goes. 1527 $self->_data_ev_enqueue( 1528 $session, $session, EN_GC, ET_GC, [], 1529 __FILE__, __LINE__, undef 1530 ); 1531} 1532 1533# Detach a session from its parent. This breaks the parent/child 1534# relationship between the current session and its parent. Basically, 1535# the current session is given to the Kernel session. Unlike with 1536# _stop, the current session's children follow their parent. 1537 1538sub detach_myself { 1539 my $self = $poe_kernel; 1540 1541 if (ASSERT_USAGE) { 1542 _confess "<us> must call detach_myself() from a running session" 1543 if $kr_active_session == $self; 1544 } 1545 1546 # Can't detach from the kernel. 1547 if ($self->_data_ses_get_parent($kr_active_session->ID) == $self) { 1548 $! = EPERM; 1549 return; 1550 } 1551 1552 my $old_parent = $self->_data_ses_get_parent($kr_active_session->ID); 1553 1554 # Tell the old parent session that the child is departing. 1555 # But not if the active event is ET_START, since that would generate 1556 # a CHILD_LOSE without a CHILD_CREATE. 1557 $self->_dispatch_event( 1558 $old_parent, $self, 1559 EN_CHILD, ET_CHILD, [ CHILD_LOSE, $kr_active_session, undef ], 1560 (caller)[1,2], undef, monotime(), -__LINE__ 1561 ) 1562 unless $kr_active_event_type & ET_START; 1563 1564 # Tell the new parent (kernel) that it's gaining a child. 1565 # (Actually it doesn't care, so we don't do that here, but this is 1566 # where the code would go if it ever does in the future.) 1567 1568 # Tell the current session that its parentage is changing. 1569 $self->_dispatch_event( 1570 $kr_active_session, $self, 1571 EN_PARENT, ET_PARENT, [ $old_parent, $self ], 1572 (caller)[1,2], undef, monotime(), -__LINE__ 1573 ); 1574 1575 $self->_data_ses_move_child($kr_active_session->ID, $self->ID); 1576 1577 # Success! 1578 return 1; 1579} 1580 1581# Detach a child from this, the parent. The session being detached 1582# must be a child of the current session. 1583 1584sub detach_child { 1585 my ($self, $child) = ($poe_kernel, @_[1..$#_]); 1586 1587 if (ASSERT_USAGE) { 1588 _confess "<us> must call detach_child() from a running session" 1589 if $kr_active_session == $self; 1590 } 1591 1592 my $child_session = $self->_resolve_session($child); 1593 unless (defined $child_session) { 1594 $self->_explain_resolve_failure($child); 1595 return; 1596 } 1597 1598 # Can't detach if it belongs to the kernel. TODO We shouldn't need 1599 # to check for this. 1600 if ($kr_active_session == $self) { 1601 $! = EPERM; 1602 return; 1603 } 1604 1605 # Can't detach if it's not a child of the current session. 1606 unless ( 1607 $self->_data_ses_is_child($kr_active_session->ID, $child_session->ID) 1608 ) { 1609 $! = EPERM; 1610 return; 1611 } 1612 1613 # Tell the current session that the child is departing. 1614 $self->_dispatch_event( 1615 $kr_active_session, $self, 1616 EN_CHILD, ET_CHILD, [ CHILD_LOSE, $child_session, undef ], 1617 (caller)[1,2], undef, monotime(), -__LINE__ 1618 ); 1619 1620 # Tell the new parent (kernel) that it's gaining a child. 1621 # (Actually it doesn't care, so we don't do that here, but this is 1622 # where the code would go if it ever does in the future.) 1623 1624 # Tell the child session that its parentage is changing. 1625 $self->_dispatch_event( 1626 $child_session, $self, 1627 EN_PARENT, ET_PARENT, [ $kr_active_session, $self ], 1628 (caller)[1,2], undef, monotime(), -__LINE__ 1629 ); 1630 1631 $self->_data_ses_move_child($child_session->ID, $self->ID); 1632 1633 # Success! 1634 return 1; 1635} 1636 1637### Helpful accessors. 1638 1639sub get_active_session { 1640 return $kr_active_session; 1641} 1642 1643sub get_active_event { 1644 return $kr_active_event; 1645} 1646 1647# FIXME - Should this exist? 1648sub get_event_count { 1649 return $kr_queue->get_item_count(); 1650} 1651 1652# FIXME - Should this exist? 1653sub get_next_event_time { 1654 return $kr_queue->get_next_priority(); 1655} 1656 1657#============================================================================== 1658# EVENTS 1659#============================================================================== 1660 1661#------------------------------------------------------------------------------ 1662# Post an event to the queue. 1663 1664sub post { 1665 my ($self, $dest_session, $event_name, @etc) = ($poe_kernel, @_[1..$#_]); 1666 1667 if (ASSERT_USAGE) { 1668 _confess "<us> destination is undefined in post()" 1669 unless defined $dest_session; 1670 _confess "<us> event is undefined in post()" unless defined $event_name; 1671 _carp( 1672 "<us> The '$event_name' event is one of POE's own. Its " . 1673 "effect cannot be achieved by posting it" 1674 ) if exists $poes_own_events{$event_name}; 1675 }; 1676 1677 # Attempt to resolve the destination session reference against 1678 # various things. 1679 1680 my $session = $self->_resolve_session($dest_session); 1681 unless (defined $session) { 1682 $self->_explain_resolve_failure($dest_session); 1683 return; 1684 } 1685 1686 # Enqueue the event for "now", which simulates FIFO in our 1687 # time-ordered queue. 1688 1689 $self->_data_ev_enqueue( 1690 $session, $kr_active_session, $event_name, ET_POST, \@etc, 1691 (caller)[1,2], $kr_active_event 1692 ); 1693 return 1; 1694} 1695 1696#------------------------------------------------------------------------------ 1697# Post an event to the queue for the current session. 1698 1699sub yield { 1700 my ($self, $event_name, @etc) = ($poe_kernel, @_[1..$#_]); 1701 1702 if (ASSERT_USAGE) { 1703 _confess "<us> must call yield() from a running session" 1704 if $kr_active_session == $self; 1705 _confess "<us> event name is undefined in yield()" 1706 unless defined $event_name; 1707 _carp( 1708 "<us> The '$event_name' event is one of POE's own. Its " . 1709 "effect cannot be achieved by yielding it" 1710 ) if exists $poes_own_events{$event_name}; 1711 }; 1712 1713 $self->_data_ev_enqueue( 1714 $kr_active_session, $kr_active_session, $event_name, ET_POST, \@etc, 1715 (caller)[1,2], $kr_active_event 1716 ); 1717 1718 undef; 1719} 1720 1721#------------------------------------------------------------------------------ 1722# Call an event handler directly. 1723 1724sub call { 1725 my ($self, $dest_session, $event_name, @etc) = ($poe_kernel, @_[1..$#_]); 1726 1727 if (ASSERT_USAGE) { 1728 _confess "<us> destination is undefined in call()" 1729 unless defined $dest_session; 1730 _confess "<us> event is undefined in call()" unless defined $event_name; 1731 _carp( 1732 "<us> The '$event_name' event is one of POE's own. Its " . 1733 "effect cannot be achieved by calling it" 1734 ) if exists $poes_own_events{$event_name}; 1735 }; 1736 1737 # Attempt to resolve the destination session reference against 1738 # various things. 1739 1740 my $session = $self->_resolve_session($dest_session); 1741 unless (defined $session) { 1742 $self->_explain_resolve_failure($dest_session); 1743 return; 1744 } 1745 1746 # Dispatch the event right now, bypassing the queue altogether. 1747 # This tends to be a Bad Thing to Do. 1748 1749 # TODO The difference between synchronous and asynchronous events 1750 # should be made more clear in the documentation, so that people 1751 # have a tendency not to abuse them. I discovered in xws that 1752 # mixing the two types makes it harder than necessary to write 1753 # deterministic programs, but the difficulty can be ameliorated if 1754 # programmers set some base rules and stick to them. 1755 1756 if (wantarray) { 1757 my @return_value = ( 1758 ($session == $kr_active_session) 1759 ? $session->_invoke_state( 1760 $session, $event_name, \@etc, (caller)[1,2], 1761 $kr_active_event 1762 ) 1763 : $self->_dispatch_event( 1764 $session, $kr_active_session, 1765 $event_name, ET_CALL, \@etc, 1766 (caller)[1,2], $kr_active_event, monotime(), -__LINE__ 1767 ) 1768 ); 1769 1770 $kr_exception and $self->_rethrow_kr_exception(); 1771 1772 $! = 0; 1773 return @return_value; 1774 } 1775 1776 if (defined wantarray) { 1777 my $return_value = ( 1778 $session == $kr_active_session 1779 ? $session->_invoke_state( 1780 $session, $event_name, \@etc, (caller)[1,2], 1781 $kr_active_event 1782 ) 1783 : $self->_dispatch_event( 1784 $session, $kr_active_session, 1785 $event_name, ET_CALL, \@etc, 1786 (caller)[1,2], $kr_active_event, monotime(), -__LINE__ 1787 ) 1788 ); 1789 1790 $kr_exception and $self->_rethrow_kr_exception(); 1791 1792 $! = 0; 1793 return $return_value; 1794 } 1795 1796 if ($session == $kr_active_session) { 1797 $session->_invoke_state( 1798 $session, $event_name, \@etc, (caller)[1,2], 1799 $kr_active_event 1800 ); 1801 } 1802 else { 1803 $self->_dispatch_event( 1804 $session, $kr_active_session, 1805 $event_name, ET_CALL, \@etc, 1806 (caller)[1,2], $kr_active_event, monotime(), -__LINE__ 1807 ); 1808 } 1809 1810 $kr_exception and $self->_rethrow_kr_exception(); 1811 1812 $! = 0; 1813 return; 1814} 1815 1816#============================================================================== 1817# DELAYED EVENTS 1818#============================================================================== 1819 1820sub alarm { 1821 my ($self, $event_name, $time, @etc) = ($poe_kernel, @_[1..$#_]); 1822 1823 if (ASSERT_USAGE) { 1824 _confess "<us> must call alarm() from a running session" 1825 if $kr_active_session == $self; 1826 _confess "<us> event name is undefined in alarm()" 1827 unless defined $event_name; 1828 _carp( 1829 "<us> The '$event_name' event is one of POE's own. Its " . 1830 "effect cannot be achieved by setting an alarm for it" 1831 ) if exists $poes_own_events{$event_name}; 1832 }; 1833 1834 unless (defined $event_name) { 1835 $self->_explain_return("invalid parameter to alarm() call"); 1836 return EINVAL; 1837 } 1838 1839 $self->_data_ev_clear_alarm_by_name($kr_active_session->ID(), $event_name); 1840 1841 # Add the new alarm if it includes a time. Calling _data_ev_enqueue 1842 # directly is faster than calling alarm_set to enqueue it. 1843 if (defined $time) { 1844 $self->_data_ev_enqueue 1845 ( $kr_active_session, $kr_active_session, 1846 $event_name, ET_ALARM, [ @etc ], 1847 (caller)[1,2], $kr_active_event, $time, 1848 ); 1849 } 1850 else { 1851 # The event queue has become empty? Stop the time watcher. 1852 $self->loop_pause_time_watcher() unless $kr_queue->get_item_count(); 1853 } 1854 1855 return 0; 1856} 1857 1858# Add an alarm without clobbering previous alarms of the same name. 1859sub alarm_add { 1860 my ($self, $event_name, $time, @etc) = ($poe_kernel, @_[1..$#_]); 1861 1862 if (ASSERT_USAGE) { 1863 _confess "<us> must call alarm_add() from a running session" 1864 if $kr_active_session == $self; 1865 _confess "<us> undefined event name in alarm_add()" 1866 unless defined $event_name; 1867 _confess "<us> undefined time in alarm_add()" unless defined $time; 1868 _carp( 1869 "<us> The '$event_name' event is one of POE's own. Its " . 1870 "effect cannot be achieved by adding an alarm for it" 1871 ) if exists $poes_own_events{$event_name}; 1872 }; 1873 1874 unless (defined $event_name and defined $time) { 1875 $self->_explain_return("invalid parameter to alarm_add() call"); 1876 return EINVAL; 1877 } 1878 1879 $self->_data_ev_enqueue 1880 ( $kr_active_session, $kr_active_session, 1881 $event_name, ET_ALARM, [ @etc ], 1882 (caller)[1,2], $kr_active_event, $time, 1883 ); 1884 1885 return 0; 1886} 1887 1888# Add a delay, which is like an alarm relative to the current time. 1889sub delay { 1890 my ($self, $event_name, $delay, @etc) = ($poe_kernel, @_[1..$#_]); 1891 my $pri = monotime(); 1892 1893 if (ASSERT_USAGE) { 1894 _confess "<us> must call delay() from a running session" 1895 if $kr_active_session == $self; 1896 _confess "<us> undefined event name in delay()" unless defined $event_name; 1897 _carp( 1898 "<us> The '$event_name' event is one of POE's own. Its " . 1899 "effect cannot be achieved by setting a delay for it" 1900 ) if exists $poes_own_events{$event_name}; 1901 }; 1902 1903 unless (defined $event_name) { 1904 $self->_explain_return("invalid parameter to delay() call"); 1905 return EINVAL; 1906 } 1907 1908 if (defined $delay) { 1909 $self->_data_ev_clear_alarm_by_name($kr_active_session->ID(), $event_name); 1910 1911 # Add the new alarm if it includes a time. Calling _data_ev_enqueue 1912 # directly is faster than calling alarm_set to enqueue it. 1913 $self->_data_ev_enqueue 1914 ( $kr_active_session, $kr_active_session, 1915 $event_name, ET_ALARM, [ @etc ], 1916 (caller)[1,2], $kr_active_event, undef, $delay, $pri+$delay 1917 ); 1918 } 1919 else { 1920 $self->alarm($event_name); 1921 } 1922 1923 return 0; 1924} 1925 1926# Add a delay without clobbering previous delays of the same name. 1927sub delay_add { 1928 my ($self, $event_name, $delay, @etc) = ($poe_kernel, @_[1..$#_]); 1929 my $pri = monotime(); 1930 1931 if (ASSERT_USAGE) { 1932 _confess "<us> must call delay_add() from a running session" 1933 if $kr_active_session == $self; 1934 _confess "<us> undefined event name in delay_add()" 1935 unless defined $event_name; 1936 _confess "<us> undefined time in delay_add()" unless defined $delay; 1937 _carp( 1938 "<us> The '$event_name' event is one of POE's own. Its " . 1939 "effect cannot be achieved by adding a delay for it" 1940 ) if exists $poes_own_events{$event_name}; 1941 }; 1942 1943 unless (defined $event_name and defined $delay) { 1944 $self->_explain_return("invalid parameter to delay_add() call"); 1945 return EINVAL; 1946 } 1947 1948 $self->_data_ev_enqueue 1949 ( $kr_active_session, $kr_active_session, 1950 $event_name, ET_ALARM, [ @etc ], 1951 (caller)[1,2], $kr_active_event, undef, $delay, $pri+$delay 1952 ); 1953 1954 return 0; 1955} 1956 1957#------------------------------------------------------------------------------ 1958# New style alarms. 1959 1960# Set an alarm. This does more *and* less than plain alarm(). It 1961# only sets alarms (that's the less part), but it also returns an 1962# alarm ID (that's the more part). 1963 1964sub alarm_set { 1965 my ($self, $event_name, $time, @etc) = ($poe_kernel, @_[1..$#_]); 1966 1967 if (ASSERT_USAGE) { 1968 _confess "<us> must call alarm_set() from a running session" 1969 if $kr_active_session == $self; 1970 } 1971 1972 unless (defined $event_name) { 1973 $self->_explain_usage("undefined event name in alarm_set()"); 1974 $! = EINVAL; 1975 return; 1976 } 1977 1978 unless (defined $time) { 1979 $self->_explain_usage("undefined time in alarm_set()"); 1980 $! = EINVAL; 1981 return; 1982 } 1983 1984 if (ASSERT_USAGE) { 1985 _carp( 1986 "<us> The '$event_name' event is one of POE's own. Its " . 1987 "effect cannot be achieved by setting an alarm for it" 1988 ) if exists $poes_own_events{$event_name}; 1989 } 1990 1991 return $self->_data_ev_enqueue 1992 ( $kr_active_session, $kr_active_session, $event_name, ET_ALARM, [ @etc ], 1993 (caller)[1,2], $kr_active_event, $time, 1994 ); 1995} 1996 1997# Remove an alarm by its ID. TODO Now that alarms and events have 1998# been recombined, this will remove an event by its ID. However, 1999# nothing returns an event ID, so nobody knows what to remove. 2000 2001sub alarm_remove { 2002 my ($self, $alarm_id) = ($poe_kernel, @_[1..$#_]); 2003 2004 if (ASSERT_USAGE) { 2005 _confess "<us> must call alarm_remove() from a running session" 2006 if $kr_active_session == $self; 2007 } 2008 2009 unless (defined $alarm_id) { 2010 $self->_explain_usage("undefined alarm id in alarm_remove()"); 2011 $! = EINVAL; 2012 return; 2013 } 2014 2015 my ($time, $event) = 2016 $self->_data_ev_clear_alarm_by_id($kr_active_session->ID(), $alarm_id); 2017 return unless defined $time; 2018 2019 # In a list context, return the alarm that was removed. In a scalar 2020 # context, return a reference to the alarm that was removed. In a 2021 # void context, return nothing. Either way this returns a defined 2022 # value when someone needs something useful from it. 2023 2024 return unless defined wantarray; 2025 return ( $event->[EV_NAME], $time, $event->[EV_ARGS] ) if wantarray; 2026 return [ $event->[EV_NAME], $time, $event->[EV_ARGS] ]; 2027} 2028 2029# Move an alarm to a new time. This virtually removes the alarm and 2030# re-adds it somewhere else. In reality, adjust_priority() is 2031# optimized for this sort of thing. 2032 2033sub alarm_adjust { 2034 my ($self, $alarm_id, $delta) = ($poe_kernel, @_[1..$#_]); 2035 2036 if (ASSERT_USAGE) { 2037 _confess "<us> must call alarm_adjust() from a running session" 2038 if $kr_active_session == $self; 2039 } 2040 2041 unless (defined $alarm_id) { 2042 $self->_explain_usage("undefined alarm id in alarm_adjust()"); 2043 $! = EINVAL; 2044 return; 2045 } 2046 2047 unless (defined $delta) { 2048 $self->_explain_usage("undefined alarm delta in alarm_adjust()"); 2049 $! = EINVAL; 2050 return; 2051 } 2052 2053 my $my_alarm = sub { 2054 $_[0]->[EV_SESSION] == $kr_active_session; 2055 }; 2056 2057 return $self->_data_ev_adjust( $alarm_id, $my_alarm, undef, $delta ); 2058} 2059 2060# A convenient function for setting alarms relative to now. It also 2061# uses whichever time() POE::Kernel can find, which may be 2062# Time::HiRes'. 2063 2064sub delay_set { 2065 # Always always always grab time() ASAP, so that the eventual 2066 # time we set the delay for is as close as possible to the time 2067 # at which they ASKED for the delay, not when we actually set it. 2068 my $t = walltime(); 2069 my $pri = monotime(); 2070 2071 # And now continue as normal 2072 my ($self, $event_name, $seconds, @etc) = ($poe_kernel, @_[1..$#_]); 2073 2074 if (ASSERT_USAGE) { 2075 _confess "<us> must call delay_set() from a running session" 2076 if $kr_active_session == $self; 2077 } 2078 2079 unless (defined $event_name) { 2080 $self->_explain_usage("undefined event name in delay_set()"); 2081 $! = EINVAL; 2082 return; 2083 } 2084 2085 if (ASSERT_USAGE) { 2086 _carp( 2087 "<us> The '$event_name' event is one of POE's own. Its " . 2088 "effect cannot be achieved by setting a delay for it" 2089 ) if exists $poes_own_events{$event_name}; 2090 } 2091 2092 unless (defined $seconds) { 2093 $self->_explain_usage("undefined seconds in delay_set()"); 2094 $! = EINVAL; 2095 return; 2096 } 2097 2098 return $self->_data_ev_enqueue 2099 ( $kr_active_session, $kr_active_session, $event_name, ET_ALARM, [ @etc ], 2100 (caller)[1,2], $kr_active_event, $t, $seconds, $pri+$seconds 2101 ); 2102} 2103 2104# Move a delay to a new offset from time(). As with alarm_adjust(), 2105# this is optimized internally for this sort of activity. 2106 2107sub delay_adjust { 2108 # Always always always grab time() ASAP, so that the eventual 2109 # time we set the delay for is as close as possible to the time 2110 # at which they ASKED for the delay, not when we actually set it. 2111 my $t = walltime(); 2112 my $pri = monotime(); 2113 2114 # And now continue as normal 2115 my ($self, $alarm_id, $seconds) = ($poe_kernel, @_[1..$#_]); 2116 2117 if (ASSERT_USAGE) { 2118 _confess "<us> must call delay_adjust() from a running session" 2119 if $kr_active_session == $self; 2120 } 2121 2122 unless (defined $alarm_id) { 2123 $self->_explain_usage("undefined delay id in delay_adjust()"); 2124 $! = EINVAL; 2125 return; 2126 } 2127 2128 unless (defined $seconds) { 2129 $self->_explain_usage("undefined delay seconds in delay_adjust()"); 2130 $! = EINVAL; 2131 return; 2132 } 2133 2134 my $my_delay = sub { 2135 $_[0]->[EV_SESSION] == $kr_active_session; 2136 }; 2137 2138 if (TRACE_EVENTS) { 2139 _warn("<ev> adjusted event $alarm_id by $seconds seconds from $t"); 2140 } 2141 2142 return $self->_data_ev_set($alarm_id, $my_delay, $t, $pri, $seconds ); 2143} 2144 2145# Remove all alarms for the current session. 2146 2147sub alarm_remove_all { 2148 my $self = $poe_kernel; 2149 2150 if (ASSERT_USAGE) { 2151 _confess "<us> must call alarm_remove_all() from a running session" 2152 if $kr_active_session == $self; 2153 } 2154 2155 # This should never happen, actually. 2156 _trap "unknown session in alarm_remove_all call" unless ( 2157 $self->_data_ses_exists($kr_active_session->ID) 2158 ); 2159 2160 # Free every alarm owned by the session. This code is ripped off 2161 # from the _stop code to flush everything. 2162 2163 my @removed = $self->_data_ev_clear_alarm_by_session( 2164 $kr_active_session->ID() 2165 ); 2166 2167 return unless defined wantarray; 2168 return @removed if wantarray; 2169 return \@removed; 2170} 2171 2172#============================================================================== 2173# SELECTS 2174#============================================================================== 2175 2176sub _internal_select { 2177 my ($self, $session, $handle, $event_name, $mode, $args) = @_; 2178 2179 # If an event is included, then we're defining a filehandle watcher. 2180 2181 if ($event_name) { 2182 $self->_data_handle_add($handle, $mode, $session, $event_name, $args); 2183 } 2184 else { 2185 $self->_data_handle_remove($handle, $mode, $session->ID); 2186 } 2187} 2188 2189# A higher-level select() that manipulates read, write and expedite 2190# selects together. 2191 2192sub select { 2193 my ($self, $handle, $event_r, $event_w, $event_e, @args) = ( 2194 $poe_kernel, @_[1..$#_] 2195 ); 2196 2197 if (ASSERT_USAGE) { 2198 _confess "<us> must call select() from a running session" 2199 if $kr_active_session == $self; 2200 _confess "<us> undefined filehandle in select()" unless defined $handle; 2201 _confess "<us> invalid filehandle in select()" 2202 unless defined fileno($handle); 2203 foreach ($event_r, $event_w, $event_e) { 2204 next unless defined $_; 2205 _carp( 2206 "<us> The '$_' event is one of POE's own. Its " . 2207 "effect cannot be achieved by setting a file watcher to it" 2208 ) if exists($poes_own_events{$_}); 2209 } 2210 } 2211 2212 $self->_internal_select( 2213 $kr_active_session, $handle, $event_r, MODE_RD, \@args 2214 ); 2215 $self->_internal_select( 2216 $kr_active_session, $handle, $event_w, MODE_WR, \@args 2217 ); 2218 $self->_internal_select( 2219 $kr_active_session, $handle, $event_e, MODE_EX, \@args 2220 ); 2221 return 0; 2222} 2223 2224# Only manipulate the read select. 2225sub select_read { 2226 my ($self, $handle, $event_name, @args) = ($poe_kernel, @_[1..$#_]); 2227 2228 if (ASSERT_USAGE) { 2229 _confess "<us> must call select_read() from a running session" 2230 if $kr_active_session == $self; 2231 _confess "<us> undefined filehandle in select_read()" 2232 unless defined $handle; 2233 _confess "<us> invalid filehandle in select_read()" 2234 unless defined fileno($handle); 2235 _carp( 2236 "<us> The '$event_name' event is one of POE's own. Its " . 2237 "effect cannot be achieved by setting a file watcher to it" 2238 ) if defined($event_name) and exists($poes_own_events{$event_name}); 2239 }; 2240 2241 $self->_internal_select( 2242 $kr_active_session, $handle, $event_name, MODE_RD, \@args 2243 ); 2244 return 0; 2245} 2246 2247# Only manipulate the write select. 2248sub select_write { 2249 my ($self, $handle, $event_name, @args) = ($poe_kernel, @_[1..$#_]); 2250 2251 if (ASSERT_USAGE) { 2252 _confess "<us> must call select_write() from a running session" 2253 if $kr_active_session == $self; 2254 _confess "<us> undefined filehandle in select_write()" 2255 unless defined $handle; 2256 _confess "<us> invalid filehandle in select_write()" 2257 unless defined fileno($handle); 2258 _carp( 2259 "<us> The '$event_name' event is one of POE's own. Its " . 2260 "effect cannot be achieved by setting a file watcher to it" 2261 ) if defined($event_name) and exists($poes_own_events{$event_name}); 2262 }; 2263 2264 $self->_internal_select( 2265 $kr_active_session, $handle, $event_name, MODE_WR, \@args 2266 ); 2267 return 0; 2268} 2269 2270# Only manipulate the expedite select. 2271sub select_expedite { 2272 my ($self, $handle, $event_name, @args) = ($poe_kernel, @_[1..$#_]); 2273 2274 if (ASSERT_USAGE) { 2275 _confess "<us> must call select_expedite() from a running session" 2276 if $kr_active_session == $self; 2277 _confess "<us> undefined filehandle in select_expedite()" 2278 unless defined $handle; 2279 _confess "<us> invalid filehandle in select_expedite()" 2280 unless defined fileno($handle); 2281 _carp( 2282 "<us> The '$event_name' event is one of POE's own. Its " . 2283 "effect cannot be achieved by setting a file watcher to it" 2284 ) if defined($event_name) and exists($poes_own_events{$event_name}); 2285 }; 2286 2287 $self->_internal_select( 2288 $kr_active_session, $handle, $event_name, MODE_EX, \@args 2289 ); 2290 return 0; 2291} 2292 2293# Turn off a handle's write mode bit without doing 2294# garbage-collection things. 2295sub select_pause_write { 2296 my ($self, $handle) = ($poe_kernel, @_[1..$#_]); 2297 2298 if (ASSERT_USAGE) { 2299 _confess "<us> must call select_pause_write() from a running session" 2300 if $kr_active_session == $self; 2301 _confess "<us> undefined filehandle in select_pause_write()" 2302 unless defined $handle; 2303 _confess "<us> invalid filehandle in select_pause_write()" 2304 unless defined fileno($handle); 2305 }; 2306 2307 return 0 unless $self->_data_handle_is_good($handle, MODE_WR); 2308 2309 $self->_data_handle_pause($handle, MODE_WR); 2310 2311 return 1; 2312} 2313 2314# Turn on a handle's write mode bit without doing garbage-collection 2315# things. 2316sub select_resume_write { 2317 my ($self, $handle) = ($poe_kernel, @_[1..$#_]); 2318 2319 if (ASSERT_USAGE) { 2320 _confess "<us> must call select_resume_write() from a running session" 2321 if $kr_active_session == $self; 2322 _confess "<us> undefined filehandle in select_resume_write()" 2323 unless defined $handle; 2324 _confess "<us> invalid filehandle in select_resume_write()" 2325 unless defined fileno($handle); 2326 }; 2327 2328 return 0 unless $self->_data_handle_is_good($handle, MODE_WR); 2329 2330 $self->_data_handle_resume($handle, MODE_WR); 2331 2332 return 1; 2333} 2334 2335# Turn off a handle's read mode bit without doing garbage-collection 2336# things. 2337sub select_pause_read { 2338 my ($self, $handle) = ($poe_kernel, @_[1..$#_]); 2339 2340 if (ASSERT_USAGE) { 2341 _confess "<us> must call select_pause_read() from a running session" 2342 if $kr_active_session == $self; 2343 _confess "<us> undefined filehandle in select_pause_read()" 2344 unless defined $handle; 2345 _confess "<us> invalid filehandle in select_pause_read()" 2346 unless defined fileno($handle); 2347 }; 2348 2349 return 0 unless $self->_data_handle_is_good($handle, MODE_RD); 2350 2351 $self->_data_handle_pause($handle, MODE_RD); 2352 2353 return 1; 2354} 2355 2356# Turn on a handle's read mode bit without doing garbage-collection 2357# things. 2358sub select_resume_read { 2359 my ($self, $handle) = ($poe_kernel, @_[1..$#_]); 2360 2361 if (ASSERT_USAGE) { 2362 _confess "<us> must call select_resume_read() from a running session" 2363 if $kr_active_session == $self; 2364 _confess "<us> undefined filehandle in select_resume_read()" 2365 unless defined $handle; 2366 _confess "<us> invalid filehandle in select_resume_read()" 2367 unless defined fileno($handle); 2368 }; 2369 2370 return 0 unless $self->_data_handle_is_good($handle, MODE_RD); 2371 2372 $self->_data_handle_resume($handle, MODE_RD); 2373 2374 return 1; 2375} 2376 2377#============================================================================== 2378# Aliases: These functions expose the internal alias accessors with 2379# extra fun parameter/return value checking. 2380#============================================================================== 2381 2382### Set an alias in the current session. 2383 2384sub alias_set { 2385 my ($self, $name) = ($poe_kernel, @_[1..$#_]); 2386 2387 if (ASSERT_USAGE) { 2388 _confess "<us> undefined alias in alias_set()" unless defined $name; 2389 }; 2390 2391 # Don't overwrite another session's alias. 2392 my $existing_session = $self->_data_alias_resolve($name); 2393 if (defined $existing_session) { 2394 if ($existing_session != $kr_active_session) { 2395 $self->_explain_usage("alias '$name' is in use by another session"); 2396 return EEXIST; 2397 } 2398 return 0; 2399 } 2400 2401 $self->_data_alias_add($kr_active_session, $name); 2402 return 0; 2403} 2404 2405### Remove an alias from the current session. 2406 2407sub alias_remove { 2408 my ($self, $name) = ($poe_kernel, @_[1..$#_]); 2409 2410 if (ASSERT_USAGE) { 2411 _confess "<us> undefined alias in alias_remove()" unless defined $name; 2412 }; 2413 2414 my $existing_session = $self->_data_alias_resolve($name); 2415 2416 unless (defined $existing_session) { 2417 $self->_explain_usage("alias '$name' does not exist"); 2418 return ESRCH; 2419 } 2420 2421 if ($existing_session != $kr_active_session) { 2422 $self->_explain_usage("alias '$name' does not belong to current session"); 2423 return EPERM; 2424 } 2425 2426 $self->_data_alias_remove($kr_active_session, $name); 2427 return 0; 2428} 2429 2430### Resolve an alias into a session. 2431 2432sub alias_resolve { 2433 my ($self, $name) = ($poe_kernel, @_[1..$#_]); 2434 2435 if (ASSERT_USAGE) { 2436 _confess "<us> undefined alias in alias_resolve()" unless defined $name; 2437 }; 2438 2439 return $self->_resolve_session($name); 2440} 2441 2442### List the aliases for a given session. 2443 2444sub alias_list { 2445 my ($self, $search_session) = ($poe_kernel, @_[1..$#_]); 2446 my $session = 2447 $self->_resolve_session($search_session || $kr_active_session); 2448 2449 unless (defined $session) { 2450 $self->_explain_resolve_failure($search_session, "nonfatal"); 2451 return; 2452 } 2453 2454 # Return whatever can be found. 2455 my @alias_list = $self->_data_alias_list($session->ID); 2456 return wantarray() ? @alias_list : $alias_list[0]; 2457} 2458 2459#============================================================================== 2460# Kernel and Session IDs 2461#============================================================================== 2462 2463# Return the Kernel's "unique" ID. There's only so much uniqueness 2464# available; machines on separate private 10/8 networks may have 2465# identical kernel IDs. The chances of a collision are vanishingly 2466# small. 2467 2468# The Kernel and Session IDs are based on Philip Gwyn's code. I hope 2469# he still can recognize it. 2470 2471sub _recalc_id { 2472 my $self = shift; 2473 2474 my $old_id = $self->[KR_ID]; 2475 2476 my $hostname = eval { (uname)[1] }; 2477 $hostname = hostname() unless defined $hostname; 2478 2479 my $new_id = $self->[KR_ID] = join( 2480 "-", $hostname, 2481 map { unpack "H*", $_ } 2482 map { pack "N", $_ } 2483 (monotime(), $$, ++$kr_id_seq) 2484 ); 2485 2486 if (defined $old_id) { 2487 $self->_data_sig_relocate_kernel_id($old_id, $new_id); 2488 $self->_data_ses_relocate_kernel_id($old_id, $new_id); 2489 $self->_data_sid_relocate_kernel_id($old_id, $new_id); 2490 $self->_data_handle_relocate_kernel_id($old_id, $new_id); 2491 $self->_data_ev_relocate_kernel_id($old_id, $new_id); 2492 $self->_data_alias_relocate_kernel_id($old_id, $new_id); 2493 } 2494} 2495 2496sub ID { $poe_kernel->[KR_ID] } 2497 2498# Resolve an ID to a session reference. This function is virtually 2499# moot now that _resolve_session does it too. This explicit call will 2500# be faster, though, so it's kept for things that can benefit from it. 2501 2502sub ID_id_to_session { 2503 my ($self, $id) = ($poe_kernel, @_[1..$#_]); 2504 2505 if (ASSERT_USAGE) { 2506 _confess "<us> undefined ID in ID_id_to_session()" unless defined $id; 2507 }; 2508 2509 my $session = $self->_data_sid_resolve($id); 2510 return $session if defined $session; 2511 2512 $self->_explain_return("ID does not exist"); 2513 $! = ESRCH; 2514 return; 2515} 2516 2517# Resolve a session reference to its corresponding ID. 2518 2519sub ID_session_to_id { 2520 my ($self, $session) = ($poe_kernel, @_[1..$#_]); 2521 2522 if (ASSERT_USAGE) { 2523 _confess "<us> undefined session in ID_session_to_id()" 2524 unless defined $session; 2525 }; 2526 2527 my $id = $self->_data_ses_resolve_to_id($session); 2528 if (defined $id) { 2529 $! = 0; 2530 return $id; 2531 } 2532 2533 $self->_explain_return("session ($session) does not exist"); 2534 $! = ESRCH; 2535 return; 2536} 2537 2538#============================================================================== 2539# Extra reference counts, to keep sessions alive when things occur. 2540# They take session IDs because they may be called from resources at 2541# times where the session reference is otherwise unknown. 2542#============================================================================== 2543 2544sub refcount_increment { 2545 my ($self, $session_id, $tag) = ($poe_kernel, @_[1..$#_]); 2546 2547 if (ASSERT_USAGE) { 2548 _confess "<us> undefined session ID in refcount_increment()" 2549 unless defined $session_id; 2550 _confess "<us> undefined reference count tag in refcount_increment()" 2551 unless defined $tag; 2552 }; 2553 2554 unless ($self->_data_ses_exists($session_id)) { 2555 $self->_explain_return("session id $session_id does not exist"); 2556 $! = ESRCH; 2557 return; 2558 } 2559 2560 my $refcount = $self->_data_extref_inc($session_id, $tag); 2561 # TODO trace it here 2562 return $refcount; 2563} 2564 2565sub refcount_decrement { 2566 my ($self, $session_id, $tag) = ($poe_kernel, @_[1..$#_]); 2567 2568 if (ASSERT_USAGE) { 2569 _confess "<us> undefined session ID in refcount_decrement()" 2570 unless defined $session_id; 2571 _confess "<us> undefined reference count tag in refcount_decrement()" 2572 unless defined $tag; 2573 }; 2574 2575 unless ($self->_data_ses_exists($session_id)) { 2576 $self->_explain_return("session id $session_id does not exist"); 2577 $! = ESRCH; 2578 return; 2579 } 2580 2581 my $refcount = $self->_data_extref_dec($session_id, $tag); 2582 2583 # TODO trace it here 2584 return $refcount; 2585} 2586 2587#============================================================================== 2588# HANDLERS 2589#============================================================================== 2590 2591# Add or remove event handlers from sessions. 2592sub state { 2593 my ($self, $event, $state_code, $state_alias) = ($poe_kernel, @_[1..$#_]); 2594 $state_alias = $event unless defined $state_alias; 2595 2596 if (ASSERT_USAGE) { 2597 _confess "<us> must call state() from a running session" 2598 if $kr_active_session == $self; 2599 _confess "<us> undefined event name in state()" unless defined $event; 2600 _confess "<us> can't call state() outside a session" if ( 2601 $kr_active_session == $self 2602 ); 2603 }; 2604 2605 if ( 2606 (ref($kr_active_session) ne '') && 2607 (ref($kr_active_session) ne 'POE::Kernel') 2608 ) { 2609 $kr_active_session->_register_state($event, $state_code, $state_alias); 2610 return 0; 2611 } 2612 2613 # TODO A terminal signal (such as UIDESTROY) kills a session. The 2614 # Kernel deallocates the session, which cascades destruction to its 2615 # HEAP. That triggers a Wheel's destruction, which calls 2616 # $kernel->state() to remove a state from the session. The session, 2617 # though, is already gone. If TRACE_RETVALS and/or ASSERT_RETVALS 2618 # is set, this causes a warning or fatal error. 2619 2620 $self->_explain_return("session ($kr_active_session) does not exist"); 2621 return ESRCH; 2622} 2623 26241; 2625 2626__END__ 2627 2628=head1 NAME 2629 2630POE::Kernel - an event-based application kernel in Perl 2631 2632=head1 SYNOPSIS 2633 2634 use POE; # auto-includes POE::Kernel and POE::Session 2635 2636 POE::Session->create( 2637 inline_states => { 2638 _start => sub { $_[KERNEL]->yield("next") }, 2639 next => sub { 2640 print "tick...\n"; 2641 $_[KERNEL]->delay(next => 1); 2642 }, 2643 }, 2644 ); 2645 2646 POE::Kernel->run(); 2647 exit; 2648 2649In the spirit of Perl, there are a lot of other ways to use POE. 2650 2651=head1 DESCRIPTION 2652 2653POE::Kernel is the heart of POE. It provides the lowest-level 2654features: non-blocking multiplexed I/O, timers, and signal watchers 2655are the most significant. Everything else is built upon this 2656foundation. 2657 2658POE::Kernel is not an event loop in itself. For that it uses one of 2659several available POE::Loop interface modules. See CPAN for modules 2660in the POE::Loop namespace. 2661 2662POE's documentation assumes the reader understands the @_ offset 2663constants (KERNEL, HEAP, ARG0, etc.). The curious or confused reader 2664will find more detailed explanation in L<POE::Session>. 2665 2666=head1 USING POE 2667 2668=head2 Literally Using POE 2669 2670POE.pm is little more than a class loader. It implements some magic 2671to cut down on the setup work. 2672 2673Parameters to C<use POE> are not treated as normal imports. Rather, 2674they're abbreviated modules to be included along with POE. 2675 2676 use POE qw(Component::Client::TCP). 2677 2678As you can see, the leading "POE::" can be omitted this way. 2679 2680POE.pm also includes POE::Kernel and POE::Session by default. These 2681two modules are used by nearly all POE-based programs. So the above 2682example is actually the equivalent of: 2683 2684 use POE; 2685 use POE::Kernel; 2686 use POE::Session; 2687 use POE::Component::Client::TCP; 2688 2689=head2 Using POE::Kernel 2690 2691POE::Kernel needs to know which event loop you want to use. This is 2692supported in three different ways: 2693 2694The first way is to use an event loop module before using POE::Kernel 2695(or POE, which loads POE::Kernel for you): 2696 2697 use Tk; # or one of several others 2698 use POE::Kernel. 2699 2700POE::Kernel scans the list of modules already loaded, and it loads an 2701appropriate POE::Loop adapter if it finds a known event loop. 2702 2703The next way is to explicitly load the POE::Loop class you want: 2704 2705 use POE qw(Loop::Gtk); 2706 2707Finally POE::Kernel's C<import()> supports more programmer-friendly 2708configuration: 2709 2710 use POE::Kernel { loop => "Gtk" }; 2711 use POE::Session; 2712 2713=head2 Anatomy of a POE-Based Application 2714 2715Programs using POE work like any other. They load required modules, 2716perform some setup, run some code, and eventually exit. Halting 2717Problem notwithstanding. 2718 2719A POE-based application loads some modules, sets up one or more 2720sessions, runs the code in those sessions, and eventually exits. 2721 2722 use POE; 2723 POE::Session->create( ... map events to code here ... ); 2724 POE::Kernel->run(); 2725 exit; 2726 2727=head2 POE::Kernel singleton 2728 2729The POE::Kernel is a singleton object; there can be only one POE::Kernel 2730instance within a process. This allows many object methods to also be 2731package methods. 2732 2733=head2 Sessions 2734 2735POE implements isolated compartments called I<sessions>. Sessions play 2736the role of tasks or threads within POE. POE::Kernel acts as POE's 2737task scheduler, doling out timeslices to each session by invoking 2738callbacks within them. 2739 2740Callbacks are not preemptive. As long as one is running, no others 2741will be dispatched. This is known as I<cooperative> multitasking. 2742Each session must cooperate by returning to the central dispatching 2743kernel. 2744 2745Cooperative multitasking vastly simplifies data sharing, since no two 2746pieces of code may alter data at once. 2747 2748A session may also take exclusive control of a program's time, if 2749necessary, by simply not returning in a timely fashion. It's even 2750possible to write completely blocking programs that use POE as a state 2751machine rather than a cooperative dispatcher. 2752 2753Every POE-based application needs at least one session. Code cannot 2754run I<within POE> without being a part of some session. Likewise, a 2755threaded program always has a "thread zero". 2756 2757Sessions in POE::Kernel should not be confused with 2758L<POE::Session|POE::Session> even though the two are inextricably 2759associated. POE::Session adapts POE::Kernel's dispatcher to a 2760particular calling convention. Other POE::Session classes exist on 2761the CPAN. Some radically alter the way event handlers are called. 2762L<http://search.cpan.org/search?query=poe+session>. 2763 2764=head2 Resources 2765 2766Resources are events and things which may create new events, such as 2767timers, I/O watchers, and even other sessions. 2768 2769POE::Kernel tracks resources on behalf of its active sessions. It 2770generates events corresponding to these resources' activity, notifying 2771sessions when it's time to do things. 2772 2773The conversation goes something like this: 2774 2775 Session: Be a dear, Kernel, and let me know when someone clicks on 2776 this widget. Thanks so much! 2777 2778 [TIME PASSES] [SFX: MOUSE CLICK] 2779 2780 Kernel: Right, then. Someone's clicked on your widget. 2781 Here you go. 2782 2783Furthermore, since the Kernel keeps track of everything sessions do, 2784it knows when a session has run out of tasks to perform. When this 2785happens, the Kernel emits a C<_stop> event at the dead session so it 2786can clean up and shutdown. 2787 2788 Kernel: Please switch off the lights and lock up; it's time to go. 2789 2790Likewise, if a session stops on its own and there still are opened 2791resource watchers, the Kernel knows about them and cleans them up on 2792the session's behalf. POE excels at long-running services because it 2793so meticulously tracks and cleans up resources. 2794 2795POE::Resources and the POE::Resource classes implement each kind of 2796resource, which are summarized here and covered in greater detail 2797later. 2798 2799=over 2 2800 2801=item Events. 2802 2803An event is a message to a sessions. Posting an event keeps both the 2804sender and the receiver alive until after the event has been 2805dispatched. This is only guaranteed if both the sender and receiver 2806are in the same process. Inter-Kernel message passing add-ons may 2807have other guarantees. Please see their documentation for details. 2808 2809The rationale is that the event is in play, so the receiver must 2810remain active for it to be dispatched. The sender remains alive in 2811case the receiver would like to send back a response. 2812 2813Posted events cannot be preemptively canceled. They tend to be 2814short-lived in practice, so this generally isn't an issue. 2815 2816=item Timers. 2817 2818Timers allow an application to send a message to the future. Once set, 2819a timer will keep the destination session active until it goes off and 2820the resulting event is dispatched. 2821 2822=item Aliases. 2823 2824Session aliases are an application-controlled way of addressing a 2825session. Aliases act as passive event watchers. As long as a session 2826has an alias, some other session may send events to that session by 2827that name. Aliases keep sessions alive as long as a process has 2828active sessions. 2829 2830If the only sessions remaining are being kept alive solely by their 2831aliases, POE::Kernel will send them a terminal L</IDLE> signal. In 2832most cases this will terminate the remaining sessions and allow the 2833program to exit. If the sessions remain in memory without waking up 2834on the C<IDLE> signal, POE::Kernel sends them a non-maskable L</ZOMBIE> 2835signal. They are then forcibly removed, and the program will finally 2836exit. 2837 2838=item I/O watchers. 2839 2840A session will remain active as long as a session is paying attention 2841to some external data source or sink. See 2842L<select_read|"select_read FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]"> 2843and 2844L<select_write|"select_write FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]">. 2845 2846=item Child sessions. 2847 2848A session acting as a parent of one or more other sessions will remain 2849active until all the child sessions stop. This may be bypassed by 2850detaching the children from the parent. 2851 2852=item Child processes. 2853 2854Child process are watched by sig_child(). The sig_child() watcher 2855will keep the watching session active until the child process has been 2856reaped by POE::Kernel and the resulting event has been dispatched. 2857 2858All other signal watchers, including using L</sig> to watch for 2859C<CHLD>, do not keep their sessions active. If you need a session to 2860remain active when it's only watching for signals, have it set an 2861alias or one of its own public reference counters. 2862 2863=item Public reference counters. 2864 2865A session will remain active as long as it has one or more nonzero 2866public (or external) reference counter. 2867 2868=back 2869 2870=head2 Session Lifespans 2871 2872"Session" as a term is somewhat overloaded. There are two related 2873concepts that share the name. First there is the class POE::Session, 2874and objects created with it or related classes. Second there is a 2875data structure within POE::Kernel that tracks the POE::Session objects 2876in play and the various resources owned by each. 2877 2878The way POE's garbage collector works is that a session object gives 2879itself to POE::Kernel at creation time. The Kernel then holds onto 2880that object as long as resources exist that require the session to 2881remain alive. When all of these resources are destroyed or released, 2882the session object has nothing left to trigger activity. POE::Kernel 2883notifies the object it's through, and cleans up its internal session 2884context. The session object is released, and self-destructs in the 2885normal Perlish fashion. 2886 2887Sessions may be stopped even if they have active resources. For 2888example, a session may fail to handle a terminal signal. In this 2889case, POE::Kernel forces the session to stop, and all resources 2890associated with the session are preemptively released. 2891 2892=head2 Events 2893 2894An event is a message that is sent from one part of the POE 2895application to another. An event consists of the event's name, 2896optional event-specific parameters and OOB information. An event may 2897be sent from the kernel, from a wheel or from a session. 2898 2899An application creates an event with L</post>, L</yield>, L</call> or 2900even L</signal>. POE::Kernel creates events in response external 2901stimulus (signals, select, etc). 2902 2903=head3 Event Handlers 2904 2905An event is handled by a function called an I<event handler>, which is 2906some code that is designated to be called when a particular event is 2907dispatched. See L</Event Handler Management> and L<POE::Session>. 2908 2909The term I<state> is often used in place of I<event handler>, 2910especially when treating sessions as event driven state machines. 2911 2912Handlers are always called in scalar context for asynchronous events 2913(i.e. via post()). Synchronous events, invoked with call(), are 2914handled in the same context that call() was called. 2915 2916Event handlers may not directly return references to objects in the 2917"POE" namespace. POE::Kernel will stringify these references to 2918prevent timing issues with certain objects' destruction. For example, 2919this error handler would cause errors because a deleted wheel would 2920not be destructed when one might think: 2921 2922 sub handle_error { 2923 warn "Got an error"; 2924 delete $_[HEAP]{wheel}; 2925 } 2926 2927The delete() call returns the deleted wheel member, which is then 2928returned implicitly by handle_error(). 2929 2930=head2 Using POE with Other Event Loops 2931 2932POE::Kernel supports any number of event loops. Two are included in 2933the base distribution. Historically, POE included other loops but they 2934were moved into a separate distribution. You can find them and other 2935loops on the CPAN. 2936 2937POE's public interfaces remain the same regardless of the event loop 2938being used. Since most graphical toolkits include some form of event 2939loop, back-end code should be portable to all of them. 2940 2941POE's cooperation with other event loops lets POE be embedded into 2942other software. The common underlying event loop drives both the 2943application and POE. For example, by using POE::Loop::Glib, one can 2944embed POE into Vim, irssi, and so on. Application scripts can then 2945take advantage of POE::Component::Client::HTTP (and everything else) 2946to do large-scale work without blocking the rest of the program. 2947 2948Because this is Perl, there are multiple ways to load an alternate 2949event loop. The simplest way is to load the event loop before loading 2950POE::Kernel. 2951 2952 use Gtk; 2953 use POE; 2954 2955Remember that POE loads POE::Kernel internally. 2956 2957POE::Kernel examines the modules loaded before it and detects that 2958L<Gtk> has been loaded. If L<POE::Loop::Gtk|POE::Loop::Gtk> is 2959available, POE loads and hooks it into POE::Kernel automatically. 2960 2961It's less mysterious to load the appropriate L<POE::Loop|POE::Loop> 2962class directly. Their names follow the format 2963C<POE::Loop::$loop_module_name>, where C<$loop_module_name> is the 2964name of the event loop module after each C<::> has been substituted 2965with an underscore. It can be abbreviated using POE's loader magic. 2966 2967 use POE qw( Loop::Event_Lib ); 2968 2969POE also recognizes XS loops, they reside in the 2970C<POE::XS::Loop::$loop_module_name> namespace. Using them may give 2971you a performance improvement on your platform, as the eventloop 2972are some of the hottest code in the system. As always, benchmark 2973your application against various loops to see which one is best for 2974your workload and platform. 2975 2976 use POE qw( XS::Loop::EPoll ); 2977 2978Please don't load the loop modules directly, because POE will not have 2979a chance to initialize it's internal structures yet. Code written like 2980this will throw errors on startup. It might look like a bug in POE, but 2981it's just the way POE is designed. 2982 2983 use POE::Loop::IO_Poll; 2984 use POE; 2985 2986POE::Kernel also supports configuration directives on its own C<use> 2987line. A loop explicitly specified this way will override the search 2988logic. 2989 2990 use POE::Kernel { loop => "Glib" }; 2991 2992Finally, one may specify the loop class by setting the POE::Loop or 2993POE::XS:Loop class name in the POE_EVENT_LOOP environment variable. 2994This mechanism was added for tests that need to specify the loop from 2995a distance. 2996 2997 BEGIN { $ENV{POE_EVENT_LOOP} = "POE::XS::Loop::Poll" } 2998 use POE; 2999 3000Of course this may also be set from your shell: 3001 3002 % export POE_EVENT_LOOP='POE::XS::Loop::Poll' 3003 % make test 3004 3005Many external event loops support their own callback mechanisms. 3006L<POE::Session|POE::Session>'s L<"postback()"|POE::Session/postback> 3007and L<"callback()"|POE::Session/callback> methods return plain Perl 3008code references that will generate POE events when called. 3009Applications can pass these code references to event loops for use as 3010callbacks. 3011 3012POE's distribution includes two event loop interfaces. CPAN holds 3013several more: 3014 3015=head3 POE::Loop::Select (bundled) 3016 3017By default POE uses its select() based loop to drive its event system. 3018This is perhaps the least efficient loop, but it is also the most 3019portable. POE optimizes for correctness above all. 3020 3021=head3 POE::Loop::IO_Poll (bundled) 3022 3023The L<IO::Poll|IO::Poll> event loop provides an alternative that 3024theoretically scales better than select(). 3025 3026=head3 POE::Loop::Event (separate distribution) 3027 3028This event loop provides interoperability with other modules that use 3029L<Event>. It may also provide a performance boost because L<Event> is 3030written in a compiled language. Unfortunately, this makes L<Event> 3031less portable than Perl's built-in select(). 3032 3033=head3 POE::Loop::Gtk (separate distribution) 3034 3035This event loop allows programs to work under the L<Gtk> graphical 3036toolkit. 3037 3038=head3 POE::Loop::Tk (separate distribution) 3039 3040This event loop allows programs to work under the L<Tk> graphical 3041toolkit. Tk has some restrictions that require POE to behave oddly. 3042 3043Tk's event loop will not run unless one or more widgets are created. 3044POE must therefore create such a widget before it can run. POE::Kernel 3045exports $poe_main_window so that the application developer may use the 3046widget (which is a L<MainWindow|Tk::MainWindow>), since POE doesn't 3047need it other than for dispatching events. 3048 3049Creating and using a different MainWindow often has an undesired 3050outcome. 3051 3052=head3 POE::Loop::EV (separate distribution) 3053 3054L<POE::Loop::EV> allows POE-based programs to use the EV event library 3055with little or no change. 3056 3057=head3 POE::Loop::Glib (separate distribution) 3058 3059L<POE::Loop::Glib> allows POE-based programs to use Glib with little 3060or no change. It also supports embedding POE-based programs into 3061applications that already use Glib. For example, we have heard that 3062POE has successfully embedded into vim, irssi and xchat via this loop. 3063 3064=head3 POE::Loop::Kqueue (separate distribution) 3065 3066L<POE::Loop::Kqueue> allows POE-based programs to transparently use 3067the BSD kqueue event library on operating systems that support it. 3068 3069=head3 POE::Loop::Prima (separate distribution) 3070 3071L<POE::Loop::Prima> allows POE-based programs to use Prima's event 3072loop with little or no change. It allows POE libraries to be used 3073within Prima applications. 3074 3075=head3 POE::Loop::Wx (separate distribution) 3076 3077L<POE::Loop::Wx> allows POE-based programs to use Wx's event loop with 3078little or no change. It allows POE libraries to be used within Wx 3079applications, such as Padre. 3080 3081=head3 POE::XS::Loop::EPoll (separate distribution) 3082 3083L<POE::XS::Loop::EPoll> allows POE components to transparently use the 3084EPoll event library on operating systems that support it. 3085 3086=head3 POE::XS::Loop::Poll (separate distribution) 3087 3088L<POE::XS::Loop::Poll> is a higher-performance C-based libpoll event 3089loop. It replaces some of POE's hot Perl code with C for better 3090performance. 3091 3092=head3 Other Event Loops (separate distributions) 3093 3094POE may be extended to handle other event loops. Developers are 3095invited to work with us to support their favorite loops. 3096 3097=head1 PUBLIC METHODS 3098 3099POE::Kernel encapsulates a lot of features. The documentation for 3100each set of features is grouped by purpose. 3101 3102=head2 Kernel Management and Accessors 3103 3104=head3 ID 3105 3106ID() currently returns POE::Kernel's unique identifier. Every 3107Kernel instance is assigned a globally unique ID at birth. 3108has_forked() alters the ID so that each forked process has a unique 3109one, too. 3110 3111 % perl -wl -MPOE -e 'print $poe_kernel->ID' 3112 macbookpoe.local-4d5305de-0000e6b8-00000001 3113 3114The content of these IDs may change from time to time. Your code 3115should not depend upon the current format. 3116 3117B<Deprecation Warning 2011-02-09> 3118 3119Your code should not depend upon ID() remaining unique. The 3120uniqueness will be removed in a future release of POE. If you require 3121unique IDs, please see one of the fine GUID and/or UUID modules on the 3122CPAN: 3123 3124 http://search.cpan.org/search?query=GUID&mode=dist 3125 http://search.cpan.org/search?query=UUID&mode=dist 3126 3127POE doesn't require globally or universally unique kernel IDs. The 3128creation and maintenance of these IDs adds overhead to POE::Kernel's 3129has_forked() method. Other modules do it better, upon demand, without 3130incurring overhead for those who don't need them. 3131 3132=head3 run 3133 3134run() runs POE::Kernel's event dispatcher. It will not return until 3135all sessions have ended. run() is a class method so a POE::Kernel 3136reference is not needed to start a program's execution. 3137 3138 use POE; 3139 POE::Session->create( ... ); # one or more 3140 POE::Kernel->run(); # set them all running 3141 exit; 3142 3143POE implements the Reactor pattern at its core. Events are dispatched 3144to functions and methods through callbacks. The code behind run() 3145waits for and dispatches events. 3146 3147run() will not return until every session has ended. This includes 3148sessions that were created while run() was running. 3149 3150POE::Kernel will print a strong message if a program creates sessions 3151but fails to call run(). Prior to this warning, we received tons of 3152bug reports along the lines of "my POE program isn't doing anything". 3153It turned out that people forgot to start an event dispatcher, so 3154events were never dispatched. 3155 3156If the lack of a run() call is deliberate, perhaps because some other 3157event loop already has control, you can avoid the message by calling 3158it before creating a session. run() at that point will initialize POE 3159and return immediately. POE::Kernel will be satisfied that run() was 3160called, although POE will not have actually taken control of the event 3161loop. 3162 3163 use POE; 3164 POE::Kernel->run(); # silence the warning 3165 POE::Session->create( ... ); 3166 exit; 3167 3168Note, however, that this varies from one event loop to another. If a 3169particular POE::Loop implementation doesn't support it, that's 3170probably a bug. Please file a bug report with the owner of the 3171relevant POE::Loop module. 3172 3173=head3 run_one_timeslice 3174 3175run_one_timeslice() dispatches any events that are due to be 3176delivered. These events include timers that are due, asynchronous 3177messages that need to be delivered, signals that require handling, and 3178notifications for files with pending I/O. Do not rely too much on 3179event ordering. run_one_timeslice() is defined by the underlying 3180event loop, and its timing may vary. 3181 3182run() is implemented similar to 3183 3184 run_one_timeslice() while $session_count > 0; 3185 3186run_one_timeslice() can be used to keep running POE::Kernel's 3187dispatcher while emulating blocking behavior. The pattern is 3188implemented with a flag that is set when some asynchronous event 3189occurs. A loop calls run_one_timeslice() until that flag is set. For 3190example: 3191 3192 my $done = 0; 3193 3194 sub handle_some_event { 3195 $done = 1; 3196 } 3197 3198 $kernel->run_one_timeslice() while not $done; 3199 3200Do be careful. The above example will spin if POE::Kernel is done but 3201$done is never set. The loop will never be done, even though there's 3202nothing left that will set $done. 3203 3204=head3 run_while SCALAR_REF 3205 3206run_while() is an B<experimental> version of run_one_timeslice() that 3207will only return when there are no more active sessions, or the value 3208of the referenced scalar becomes false. 3209 3210Here's a version of the run_one_timeslice() example using run_while() 3211instead: 3212 3213 my $job_count = 3; 3214 3215 sub handle_some_event { 3216 $job_count--; 3217 } 3218 3219 $kernel->run_while(\$job_count); 3220 3221=head3 has_forked 3222 3223 my $pid = fork(); 3224 die "Unable to fork" unless defined $pid; 3225 unless( $pid ) { 3226 $poe_kernel->has_forked; 3227 } 3228 3229Inform the kernel that it is now running in a new process. This allows the 3230kernel to reset some internal data to adjust to the new situation. 3231 3232has_forked() must be called in the child process if you wish to run the same 3233kernel. However, if you want the child process to have new kernel, you must 3234call L</stop> instead. 3235 3236B<Note:> POE's internals will detect if a fork occurred before C<run()> and will 3237call C<has_forked()> automatically. If you are unsure whether you need to call it 3238or not, please enable L</ASSERT_USAGE> and POE will emit a warning if it's necessary. 3239 3240=head3 stop 3241 3242stop() causes POE::Kernel->run() to return early. It does this by 3243emptying the event queue, freeing all used resources, and stopping 3244every active session. stop() is not meant to be used lightly. 3245Proceed with caution. 3246 3247Caveats: 3248 3249The session that calls stop() will not be fully DESTROYed until it 3250returns. Invoking an event handler in the session requires a 3251reference to that session, and weak references are prohibited in POE 3252for backward compatibility reasons, so it makes sense that the last 3253session won't be garbage collected right away. 3254 3255Sessions are not notified about their destruction. If anything relies 3256on _stop being delivered, it will break and/or leak memory. 3257 3258stop() is still considered experimental. It was added to improve fork() 3259support for L<POE::Wheel::Run|POE::Wheel::Run>. If it proves unfixably 3260problematic, it will be removed without much notice. 3261 3262stop() is advanced magic. Programmers who think they need it are 3263invited to become familiar with its source. 3264 3265See L<POE::Wheel::Run/Running POE::Kernel in the Child> for an example 3266of how to use this facility. 3267 3268=head2 Asynchronous Messages (FIFO Events) 3269 3270Asynchronous messages are events that are dispatched in the order in 3271which they were enqueued (the first one in is the first one out, 3272otherwise known as first-in/first-out, or FIFO order). These methods 3273enqueue new messages for delivery. The act of enqueuing a message 3274keeps the sender alive at least until the message is delivered. 3275 3276=head3 post DESTINATION, EVENT_NAME [, PARAMETER_LIST] 3277 3278post() enqueues a message to be dispatched to a particular DESTINATION 3279session. The message will be handled by the code associated with 3280EVENT_NAME. If a PARAMETER_LIST is included, its values will also be 3281passed along. 3282 3283 POE::Session->create( 3284 inline_states => { 3285 _start => sub { 3286 $_[KERNEL]->post( $_[SESSION], "event_name", 0 ); 3287 }, 3288 event_name => sub { 3289 print "$_[ARG0]\n"; 3290 $_[KERNEL]->post( $_[SESSION], "event_name", $_[ARG0] + 1 ); 3291 }, 3292 } 3293 ); 3294 3295post() returns a Boolean value indicating whether the message was 3296successfully enqueued. If post() returns false, $! is set to explain 3297the failure: 3298 3299ESRCH ("No such process") - The DESTINATION session did not exist at 3300the time post() was called. 3301 3302=head3 yield EVENT_NAME [, PARAMETER_LIST] 3303 3304yield() is a shortcut for post() where the destination session is the 3305same as the sender. This example is equivalent to the one for post(): 3306 3307 POE::Session->create( 3308 inline_states => { 3309 _start => sub { 3310 $_[KERNEL]->yield( "event_name", 0 ); 3311 }, 3312 event_name => sub { 3313 print "$_[ARG0]\n"; 3314 $_[KERNEL]->yield( "event_name", $_[ARG0] + 1 ); 3315 }, 3316 } 3317 ); 3318 3319As with post(), yield() returns right away, and the enqueued 3320EVENT_NAME is dispatched later. This may be confusing if you're 3321already familiar with threading. 3322 3323yield() should always succeed, so it does not return a meaningful 3324value. 3325 3326=head2 Synchronous Messages 3327 3328It is sometimes necessary for code to be invoked right away. For 3329example, some resources must be serviced right away, or they'll 3330faithfully continue reporting their readiness. These reports would 3331appear as a stream of duplicate events. Synchronous events can also 3332prevent data from going stale between the time an event is enqueued 3333and the time it's delivered. 3334 3335Synchronous event handlers preempt POE's event queue, so they should 3336perform simple tasks of limited duration. Synchronous events that 3337need to do more than just service a resource should pass the 3338resource's information to an asynchronous handler. Otherwise 3339synchronous operations will occur out of order in relation to 3340asynchronous events. It's very easy to have race conditions or break 3341causality this way, so try to avoid it unless you're okay with the 3342consequences. 3343 3344POE provides these ways to call message handlers right away. 3345 3346=head3 call DESTINATION, EVENT_NAME [, PARAMETER_LIST] 3347 3348call()'s semantics are nearly identical to post()'s. call() invokes a 3349DESTINATION's handler associated with an EVENT_NAME. An optional 3350PARAMETER_LIST will be passed along to the message's handler. The 3351difference, however, is that the handler will be invoked immediately, 3352even before call() returns. 3353 3354call() returns the value returned by the EVENT_NAME handler. It can 3355do this because the handler is invoked before call() returns. call() 3356can therefore be used as an accessor, although there are better ways 3357to accomplish simple accessor behavior. 3358 3359 POE::Session->create( 3360 inline_states => { 3361 _start => sub { 3362 print "Got: ", $_[KERNEL]->call($_[SESSION], "do_now"), "\n"; 3363 }, 3364 do_now => sub { 3365 return "some value"; 3366 } 3367 } 3368 ); 3369 3370The L<POE::Wheel|POE::Wheel> classes uses call() to synchronously deliver I/O 3371notifications. This avoids a host of race conditions. 3372 3373call() may fail in the same way and for the same reasons as post(). 3374On failure, $! is set to some nonzero value indicating why. Since 3375call() may return undef as a matter of course, it's recommended that 3376$! be checked for the error condition as well as the explanation. 3377 3378ESRCH ("No such process") - The DESTINATION session did not exist at 3379the time post() was called. 3380 3381=head2 Timer Events (Delayed Messages) 3382 3383It's often useful to wait for a certain time or until a certain amount 3384of time has passed. POE supports this with events that are deferred 3385until either an absolute time ("alarms") or until a certain duration 3386of time has elapsed ("delays"). 3387 3388Timer interfaces are further divided into two groups. One group identifies 3389timers by the names of their associated events. Another group identifies 3390timers by a unique identifier returned by the timer constructors. 3391Technically, the two are both name-based, but the "identifier-based" timers 3392provide a second, more specific handle to identify individual timers. 3393 3394Timers may only be set up for the current session. This design was 3395modeled after alarm() and SIGALRM, which only affect the current UNIX 3396process. Each session has a separate namespace for timer names. 3397Timer methods called in one session cannot affect the timers in 3398another. As you may have noticed, quite a lot of POE's API is 3399designed to prevent sessions from interfering with each other. 3400 3401The best way to simulate deferred inter-session messages is to send an 3402immediate message that causes the destination to set a timer. The 3403destination's timer then defers the action requested of it. This way 3404is preferred because the time spent communicating the request between 3405sessions may not be trivial, especially if the sessions are separated 3406by a network. The destination can determine how much time remains on 3407the requested timer and adjust its wait time accordingly. 3408 3409=head3 Name-Based Timers 3410 3411Name-based timers are identified by the event names used to set them. 3412It is possible for different sessions to use the same timer event names, 3413since each session is a separate compartment with its own timer namespace. 3414It is possible for a session to have multiple timers for a given event, 3415but results may be surprising. Be careful to use the right timer methods. 3416 3417The name-based timer methods are alarm(), alarm_add(), delay(), and 3418delay_add(). 3419 3420=head4 alarm EVENT_NAME [, EPOCH_TIME [, PARAMETER_LIST] ] 3421 3422alarm() clears all existing timers in the current session with the 3423same EVENT_NAME. It then sets a new timer, named EVENT_NAME, that 3424will fire EVENT_NAME at the current session when EPOCH_TIME has been 3425reached. An optional PARAMETER_LIST may be passed along to the 3426timer's handler. 3427 3428Omitting the EPOCH_TIME and subsequent parameters causes alarm() to 3429clear the EVENT_NAME timers in the current session without setting a 3430new one. 3431 3432EPOCH_TIME is the UNIX epoch time. You know, seconds since midnight, 34331970-01-01. POE uses Time::HiRes::time(), which allows EPOCH_TIME to 3434be (or include) fractional seconds. 3435 3436POE supports fractional seconds, but accuracy falls off steeply after 34371/100 second. Mileage will vary depending on your CPU speed and your 3438OS time resolution. 3439 3440Be sure to use Time::HiRes::time() rather than Perl's built-in time() 3441if sub-second accuracy matters at all. The built-in time() returns 3442floor(Time::HiRes::time()), which is nearly always some fraction of a 3443second in the past. For example the high-resolution time might be 34441200941422.89996. At that same instant, time() would be 1200941422. 3445An alarm for time() + 0.5 would be 0.39996 seconds in the past, so it 3446would be dispatched immediately (if not sooner). 3447 3448POE's event queue is time-ordered, so a timer due before time() will 3449be delivered ahead of other events but not before timers with even 3450earlier due times. Therefore an alarm() with an EPOCH_TIME before 3451time() jumps ahead of the queue. 3452 3453All timers are implemented identically internally, regardless of how 3454they are set. alarm() will therefore blithely clear timers set by 3455other means. 3456 3457 POE::Session->create( 3458 inline_states => { 3459 _start => sub { 3460 $_[KERNEL]->alarm( tick => time() + 1, 0 ); 3461 }, 3462 tick => sub { 3463 print "tick $_[ARG0]\n"; 3464 $_[KERNEL]->alarm( tock => time() + 1, $_[ARG0] + 1 ); 3465 }, 3466 tock => sub { 3467 print "tock $_[ARG0]\n"; 3468 $_[KERNEL]->alarm( tick => time() + 1, $_[ARG0] + 1 ); 3469 }, 3470 } 3471 ); 3472 3473alarm() returns 0 on success or a true value on failure. Usually 3474EINVAL to signal an invalid parameter, such as an undefined 3475EVENT_NAME. 3476 3477=head4 alarm_add EVENT_NAME, EPOCH_TIME [, PARAMETER_LIST] 3478 3479alarm_add() is used to add a new alarm timer named EVENT_NAME without 3480clearing existing timers. EPOCH_TIME is a required parameter. 3481Otherwise the semantics are identical to alarm(). 3482 3483A program may use alarm_add() without first using alarm(). 3484 3485 POE::Session->create( 3486 inline_states => { 3487 _start => sub { 3488 $_[KERNEL]->alarm_add( tick => time() + 1.0, 1_000_000 ); 3489 $_[KERNEL]->alarm_add( tick => time() + 1.5, 2_000_000 ); 3490 }, 3491 tick => sub { 3492 print "tick $_[ARG0]\n"; 3493 $_[KERNEL]->alarm_add( tock => time() + 1, $_[ARG0] + 1 ); 3494 }, 3495 tock => sub { 3496 print "tock $_[ARG0]\n"; 3497 $_[KERNEL]->alarm_add( tick => time() + 1, $_[ARG0] + 1 ); 3498 }, 3499 } 3500 ); 3501 3502alarm_add() returns 0 on success or EINVAL if EVENT_NAME or EPOCH_TIME 3503is undefined. 3504 3505=head4 delay EVENT_NAME [, DURATION_SECONDS [, PARAMETER_LIST] ] 3506 3507delay() clears all existing timers in the current session with the 3508same EVENT_NAME. It then sets a new timer, named EVENT_NAME, that 3509will fire EVENT_NAME at the current session when DURATION_SECONDS have 3510elapsed from "now". An optional PARAMETER_LIST may be passed along to 3511the timer's handler. 3512 3513Omitting the DURATION_SECONDS and subsequent parameters causes delay() 3514to clear the EVENT_NAME timers in the current session without setting 3515a new one. 3516 3517DURATION_SECONDS may be or include fractional seconds. As with all of 3518POE's timers, accuracy falls off steeply after 1/100 second. Mileage 3519will vary depending on your CPU speed and your OS time resolution. 3520 3521POE's event queue is time-ordered, so a timer due before time() will 3522be delivered ahead of other events but not before timers with even 3523earlier due times. Therefore a delay () with a zero or negative 3524DURATION_SECONDS jumps ahead of the queue. 3525 3526delay() may be considered a shorthand form of alarm(), but there are 3527subtle differences in timing issues. This code is roughly equivalent 3528to the alarm() example. 3529 3530 POE::Session->create( 3531 inline_states => { 3532 _start => sub { 3533 $_[KERNEL]->delay( tick => 1, 0 ); 3534 }, 3535 tick => sub { 3536 print "tick $_[ARG0]\n"; 3537 $_[KERNEL]->delay( tock => 1, $_[ARG0] + 1 ); 3538 }, 3539 tock => sub { 3540 print "tock $_[ARG0]\n"; 3541 $_[KERNEL]->delay( tick => 1, $_[ARG0] + 1 ); 3542 }, 3543 } 3544 ); 3545 3546delay() returns 0 on success or a reason for failure: EINVAL if 3547EVENT_NAME is undefined. 3548 3549=head4 delay_add EVENT_NAME, DURATION_SECONDS [, PARAMETER_LIST] 3550 3551delay_add() is used to add a new delay timer named EVENT_NAME without 3552clearing existing timers. DURATION_SECONDS is a required parameter. 3553Otherwise the semantics are identical to delay(). 3554 3555A program may use delay_add() without first using delay(). 3556 3557 POE::Session->create( 3558 inline_states => { 3559 _start => sub { 3560 $_[KERNEL]->delay_add( tick => 1.0, 1_000_000 ); 3561 $_[KERNEL]->delay_add( tick => 1.5, 2_000_000 ); 3562 }, 3563 tick => sub { 3564 print "tick $_[ARG0]\n"; 3565 $_[KERNEL]->delay_add( tock => 1, $_[ARG0] + 1 ); 3566 }, 3567 tock => sub { 3568 print "tock $_[ARG0]\n"; 3569 $_[KERNEL]->delay_add( tick => 1, $_[ARG0] + 1 ); 3570 }, 3571 } 3572 ); 3573 3574delay_add() returns 0 on success or EINVAL if EVENT_NAME or EPOCH_TIME 3575is undefined. 3576 3577=head3 Identifier-Based Timers 3578 3579A second way to manage timers is through identifiers. Setting an 3580alarm or delay with the "identifier" methods allows a program to 3581manipulate several timers with the same name in the same session. As 3582covered in alarm() and delay() however, it's possible to mix named and 3583identified timer calls, but the consequences may not always be 3584expected. 3585 3586=head4 alarm_set EVENT_NAME, EPOCH_TIME [, PARAMETER_LIST] 3587 3588alarm_set() sets an alarm, returning a unique identifier that can be 3589used to adjust or remove the alarm later. Unlike alarm(), it does not 3590first clear existing timers with the same EVENT_NAME. Otherwise the 3591semantics are identical to alarm(). 3592 3593 POE::Session->create( 3594 inline_states => { 3595 _start => sub { 3596 $_[HEAP]{alarm_id} = $_[KERNEL]->alarm_set( 3597 party => time() + 1999 3598 ); 3599 $_[KERNEL]->delay(raid => 1); 3600 }, 3601 raid => sub { 3602 $_[KERNEL]->alarm_remove( delete $_[HEAP]{alarm_id} ); 3603 }, 3604 } 3605 ); 3606 3607alarm_set() returns false if it fails and sets $! with the 3608explanation. $! will be EINVAL if EVENT_NAME or TIME is undefined. 3609 3610=head4 alarm_adjust ALARM_ID, DELTA_SECONDS 3611 3612alarm_adjust() adjusts an existing timer's due time by DELTA_SECONDS, 3613which may be positive or negative. It may even be zero, but that's 3614not as useful. On success, it returns the timer's new due time since 3615the start of the UNIX epoch. 3616 3617It's possible to alarm_adjust() timers created by delay_set() as well 3618as alarm_set(). 3619 3620This example moves an alarm's due time ten seconds earlier. 3621 3622 use POSIX qw(strftime); 3623 3624 POE::Session->create( 3625 inline_states => { 3626 _start => sub { 3627 $_[HEAP]{alarm_id} = $_[KERNEL]->alarm_set( 3628 party => time() + 1999 3629 ); 3630 $_[KERNEL]->delay(postpone => 1); 3631 }, 3632 postpone => sub { 3633 my $new_time = $_[KERNEL]->alarm_adjust( 3634 $_[HEAP]{alarm_id}, -10 3635 ); 3636 print( 3637 "Now we're gonna party like it's ", 3638 strftime("%F %T", gmtime($new_time)), "\n" 3639 ); 3640 }, 3641 } 3642 ); 3643 3644alarm_adjust() returns Boolean false if it fails, setting $! to the 3645reason why. $! may be EINVAL if ALARM_ID or DELTA_SECONDS are 3646undefined. It may be ESRCH if ALARM_ID no longer refers to a pending 3647timer. $! may also contain EPERM if ALARM_ID is valid but belongs to 3648a different session. 3649 3650=head4 alarm_remove ALARM_ID 3651 3652alarm_remove() removes the alarm identified by ALARM_ID. ALARM_ID 3653comes from a previous alarm_set() or delay_set() call. 3654 3655Upon success, alarm_remove() returns something true based on its 3656context. In a list context, it returns three things: The removed 3657alarm's event name, the UNIX time it was due to go off, and a 3658reference to the PARAMETER_LIST (if any) assigned to the timer when it 3659was created. If necessary, the timer can be re-set with this 3660information. 3661 3662 POE::Session->create( 3663 inline_states => { 3664 _start => sub { 3665 $_[HEAP]{alarm_id} = $_[KERNEL]->alarm_set( 3666 party => time() + 1999 3667 ); 3668 $_[KERNEL]->delay(raid => 1); 3669 }, 3670 raid => sub { 3671 my ($name, $time, $param) = $_[KERNEL]->alarm_remove( 3672 $_[HEAP]{alarm_id} 3673 ); 3674 print( 3675 "Removed alarm for event $name due at $time with @$param\n" 3676 ); 3677 3678 # Or reset it, if you'd like. Possibly after modification. 3679 $_[KERNEL]->alarm_set($name, $time, @$param); 3680 }, 3681 } 3682 ); 3683 3684In a scalar context, it returns a reference to a list of the three 3685things above. 3686 3687 # Remove and reset an alarm. 3688 my $alarm_info = $_[KERNEL]->alarm_remove( $alarm_id ); 3689 my $new_id = $_[KERNEL]->alarm_set( 3690 $alarm_info[0], $alarm_info[1], @{$alarm_info[2]} 3691 ); 3692 3693Upon failure, however, alarm_remove() returns a Boolean false value 3694and sets $! with the reason why the call failed: 3695 3696EINVAL ("Invalid argument") indicates a problem with one or more 3697parameters, usually an undefined ALARM_ID. 3698 3699ESRCH ("No such process") indicates that ALARM_ID did not refer to a 3700pending alarm. 3701 3702EPERM ("Operation not permitted"). A session cannot remove an alarm 3703it does not own. 3704 3705=head4 alarm_remove_all 3706 3707alarm_remove_all() removes all the pending timers for the current 3708session, regardless of creation method or type. This method takes no 3709arguments. It returns information about the alarms that were removed, 3710either as a list of alarms or a list reference depending whether 3711alarm_remove_all() is called in scalar or list context. 3712 3713Each removed alarm's information is identical to the format explained 3714in alarm_remove(). 3715 3716 sub some_event_handler { 3717 my @removed_alarms = $_[KERNEL]->alarm_remove_all(); 3718 foreach my $alarm (@removed_alarms) { 3719 my ($name, $time, $param) = @$alarm; 3720 ...; 3721 } 3722 } 3723 3724=head4 delay_set EVENT_NAME, DURATION_SECONDS [, PARAMETER_LIST] 3725 3726delay_set() sets a timer for DURATION_SECONDS in the future. The 3727timer will be dispatched to the code associated with EVENT_NAME in the 3728current session. An optional PARAMETER_LIST will be passed through to 3729the handler. It returns the same sort of things that alarm_set() 3730does. 3731 3732 POE::Session->create( 3733 inline_states => { 3734 _start => sub { 3735 $_[KERNEL]->delay_set("later", 5, "hello", "world"); 3736 }, 3737 later => sub { 3738 print "@_[ARG0..#$_]\n"; 3739 } 3740 } 3741 ); 3742 3743=head4 delay_adjust ALARM_ID, SECONDS_FROM_NOW 3744 3745delay_adjust() changes a timer's due time to be SECONDS_FROM_NOW. 3746It's useful for refreshing watchdog- or timeout-style timers. On 3747success it returns the new absolute UNIX time the timer will be due. 3748 3749It's possible for delay_adjust() to adjust timers created by 3750alarm_set() as well as delay_set(). 3751 3752 use POSIX qw(strftime); 3753 3754 POE::Session->create( 3755 inline_states => { 3756 # Setup. 3757 # ... omitted. 3758 3759 got_input => sub { 3760 my $new_time = $_[KERNEL]->delay_adjust( 3761 $_[HEAP]{input_timeout}, 60 3762 ); 3763 print( 3764 "Refreshed the input timeout. Next may occur at ", 3765 strftime("%F %T", gmtime($new_time)), "\n" 3766 ); 3767 }, 3768 } 3769 ); 3770 3771On failure it returns Boolean false and sets $! to a reason for the 3772failure. See the explanation of $! for alarm_adjust(). 3773 3774=head4 delay_remove is not needed 3775 3776There is no delay_remove(). Timers are all identical internally, so 3777alarm_remove() will work with timer IDs returned by delay_set(). 3778 3779=head4 delay_remove_all is not needed 3780 3781There is no delay_remove_all(). Timers are all identical internally, 3782so alarm_remove_all() clears them all regardless how they were 3783created. 3784 3785=head3 Comparison 3786 3787Below is a table to help compare the various delayed message-sending methods 3788 3789 +-----------+------------------+---------------------+------------+ 3790 | | time argument | clears other events | returns on | 3791 | method | passed to method | of the same name | success | 3792 +-----------+------------------+---------------------+------------+ 3793 | delay_set | seconds from now | N | alarm_id | 3794 | delay | seconds from now | Y | 0 (false) | 3795 | alarm_set | unix epoch time | N | alarm_id | 3796 | alarm | unix epoch time | Y | 0 (false) | 3797 +-----------+------------------+---------------------+------------+ 3798 3799=head2 Session Identifiers (IDs and Aliases) 3800 3801A session may be referred to by its object references (either blessed 3802or stringified), a session ID, or one or more symbolic names we call 3803aliases. 3804 3805Every session is represented by an object, so session references are 3806fairly straightforward. POE::Kernel may reference these objects. For 3807instance, post() may use $_[SENDER] as a destination: 3808 3809 POE::Session->create( 3810 inline_states => { 3811 _start => sub { $_[KERNEL]->alias_set("echoer") }, 3812 ping => sub { 3813 $_[KERNEL]->post( $_[SENDER], "pong", @_[ARG0..$#_] ); 3814 } 3815 } 3816 ); 3817 3818POE also recognized stringified Session objects for convenience and as 3819a form of weak reference. Here $_[SENDER] is wrapped in quotes to 3820stringify it: 3821 3822 POE::Session->create( 3823 inline_states => { 3824 _start => sub { $_[KERNEL]->alias_set("echoer") }, 3825 ping => sub { 3826 $_[KERNEL]->post( "$_[SENDER]", "pong", @_[ARG0..$#_] ); 3827 } 3828 } 3829 ); 3830 3831Every session is assigned a unique ID at creation time. No two active 3832sessions will have the same ID, but IDs may be reused over time. The 3833combination of a kernel ID and a session ID should be sufficient as a 3834global unique identifier. 3835 3836 POE::Session->create( 3837 inline_states => { 3838 _start => sub { $_[KERNEL]->alias_set("echoer") }, 3839 ping => sub { 3840 $_[KERNEL]->delay( 3841 pong_later => rand(5), $_[SENDER]->ID, @_[ARG0..$#_] 3842 ); 3843 }, 3844 pong_later => sub { 3845 $_[KERNEL]->post( $_[ARG0], "pong", @_[ARG1..$#_] ); 3846 } 3847 } 3848 ); 3849 3850Kernels also maintain a global session namespace or dictionary from which 3851may be used to map a symbolic aliases to a session. Once an alias is mapping 3852has been created, that alias may be used to refer to the session wherever a 3853session may be specified. 3854 3855In the previous examples, each echoer service has set an "echoer" 3856alias. Another session can post a ping request to the echoer session 3857by using that alias rather than a session object or ID. For example: 3858 3859 POE::Session->create( 3860 inline_states => { 3861 _start => sub { $_[KERNEL]->post(echoer => ping => "whee!" ) }, 3862 pong => sub { print "@_[ARG0..$#_]\n" } 3863 } 3864 ); 3865 3866A session with an alias will not stop until all other activity has stopped. 3867Aliases are treated as a kind of event watcher. Events come from active 3868sessions. Aliases therefore become useless when there are no active 3869sessions left. Rather than leaving the program running in a "zombie" state, 3870POE detects this deadlock condition and triggers a cleanup. See 3871L</Signal Classes> for more information. 3872 3873=head3 alias_set ALIAS 3874 3875alias_set() maps an ALIAS in POE::Kernel's dictionary to the 3876current session. The ALIAS may then be used nearly everywhere a session 3877reference, stringified reference, or ID is expected. 3878 3879Sessions may have more than one alias. Each alias must be defined in 3880a separate alias_set() call. A single alias may not refer to more 3881than one session. 3882 3883Multiple alias examples are above. 3884 3885alias_set() returns 0 on success, or a nonzero failure indicator: 3886EEXIST ("File exists") indicates that the alias is already assigned to 3887to a different session. 3888 3889=head3 alias_remove ALIAS 3890 3891alias_remove() removes an ALIAS for the current session from 3892POE::Kernel's dictionary. The ALIAS will no longer refer to the 3893current session. This does not negatively affect events already 3894posted to POE's queue. Alias resolution occurs at post() time, not at 3895delivery time. 3896 3897 POE::Session->create( 3898 inline_states => { 3899 _start => sub { 3900 $_[KERNEL]->alias_set("short_window"); 3901 $_[KERNEL]->delay(close_window => 1); 3902 }, 3903 close_window => { 3904 $_[KERNEL]->alias_remove("short_window"); 3905 } 3906 } 3907 ); 3908 3909alias_remove() returns 0 on success or a nonzero failure code: ESRCH 3910("No such process") indicates that the ALIAS is not currently in 3911POE::Kernel's dictionary. EPERM ("Operation not permitted") means 3912that the current session may not remove the ALIAS because it is in use 3913by some other session. 3914 3915=head3 alias_resolve ALIAS 3916 3917alias_resolve() returns a session reference corresponding to a given 3918ALIAS. Actually, the ALIAS may be a stringified session reference, a 3919session ID, or an alias previously registered by alias_set(). 3920 3921One use for alias_resolve() is to detect whether another session has 3922gone away: 3923 3924 unless (defined $_[KERNEL]->alias_resolve("Elvis")) { 3925 print "Elvis has left the building.\n"; 3926 } 3927 3928As previously mentioned, alias_resolve() returns a session reference 3929or undef on failure. Failure also sets $! to ESRCH ("No such 3930process") when the ALIAS is not currently in POE::Kernel's. 3931 3932=head3 alias_list [SESSION_REFERENCE] 3933 3934alias_list() returns a list of aliases associated with a specific 3935SESSION, or with the current session if SESSION is omitted. 3936alias_list() returns an empty list if the requested SESSION has no 3937aliases. 3938 3939SESSION may be a session reference (blessed or stringified), a session 3940ID, or a session alias. 3941 3942 POE::Session->create( 3943 inline_states => { 3944 $_[KERNEL]->alias_set("mi"); 3945 print( 3946 "The names I call myself: ", 3947 join(", ", $_[KERNEL]->alias_list()), 3948 "\n" 3949 ); 3950 } 3951 ); 3952 3953=head3 ID_id_to_session SESSION_ID 3954 3955ID_id_to_session() translates a session ID into a session reference. 3956It's a special-purpose subset of alias_resolve(), so it's a little 3957faster and somewhat less flexible. 3958 3959 unless (defined $_[KERNEL]->ID_id_to_session($session_id)) { 3960 print "Session $session_id doesn't exist.\n"; 3961 } 3962 3963ID_id_to_session() returns undef if a lookup failed. $! will be set 3964to ESRCH ("No such process"). 3965 3966=head3 ID_session_to_id SESSION_REFERENCE 3967 3968ID_session_to_id() converts a blessed or stringified SESSION_REFERENCE 3969into a session ID. It's more practical for stringified references, as 3970programs can call the POE::Session ID() method on the blessed ones. 3971These statements are equivalent: 3972 3973 $id = $_[SENDER]->ID(); 3974 $id = $_[KERNEL]->ID_session_to_id($_[SENDER]); 3975 $id = $_[KERNEL]->ID_session_to_id("$_[SENDER]"); 3976 3977As with other POE::Kernel lookup methods, ID_session_to_id() returns 3978undef on failure, setting $! to ESRCH ("No such process"). 3979 3980=head2 I/O Watchers (Selects) 3981 3982No event system would be complete without the ability to 3983asynchronously watch for I/O events. POE::Kernel implements the 3984lowest level watchers, which are called "selects" because they were 3985historically implemented using Perl's built-in select(2) function. 3986 3987Applications handle I/O readiness events by performing some activity 3988on the underlying filehandle. Read-readiness might be handled by 3989reading from the handle. Write-readiness by writing to it. 3990 3991All I/O watcher events include two parameters. C<ARG0> contains the 3992handle that is ready for work. C<ARG1> contains an integer describing 3993what's ready. 3994 3995 sub handle_io { 3996 my ($handle, $mode) = @_[ARG0, ARG1]; 3997 print "File $handle is ready for "; 3998 if ($mode == 0) { 3999 print "reading"; 4000 } 4001 elsif ($mode == 1) { 4002 print "writing"; 4003 } 4004 elsif ($mode == 2) { 4005 print "out-of-band reading"; 4006 } 4007 else { 4008 die "unknown mode $mode"; 4009 } 4010 print "\n"; 4011 # ... do something here 4012 } 4013 4014The remaining parameters, C<@_[ARG2..$%_]>, contain additional 4015parameters that were passed to the POE::Kernel method that created the 4016watcher. 4017 4018POE::Kernel conditions filehandles to be 8-bit clean and non-blocking. 4019Programs that need them conditioned differently should set them up 4020after starting POE I/O watchers. If you are running a Perl older than 40215.8.1 and is using tied filehandles, you need to set non-blocking mode 4022yourself as L<IO::Handle> does not work well. 4023See L<https://rt.cpan.org/Ticket/Display.html?id=67545> for more info. 4024 4025I/O watchers will prevent sessions from stopping. 4026 4027=head3 select_read FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ] 4028 4029select_read() starts or stops the current session from watching for 4030incoming data on a given FILE_HANDLE. The watcher is started if 4031EVENT_NAME is specified, or stopped if it's not. 4032ADDITIONAL_PARAMETERS, if specified, will be passed to the EVENT_NAME 4033handler as C<@_[ARG2..$#_]>. 4034 4035 POE::Session->create( 4036 inline_states => { 4037 _start => sub { 4038 $_[HEAP]{socket} = IO::Socket::INET->new( 4039 PeerAddr => "localhost", 4040 PeerPort => 25, 4041 ); 4042 $_[KERNEL]->select_read( $_[HEAP]{socket}, "got_input" ); 4043 $_[KERNEL]->delay(timed_out => 1); 4044 }, 4045 got_input => sub { 4046 my $socket = $_[ARG0]; 4047 while (sysread($socket, my $buf = "", 8192)) { 4048 print $buf; 4049 } 4050 }, 4051 timed_out => sub { 4052 $_[KERNEL]->select_read( delete $_[HEAP]{socket} ); 4053 }, 4054 } 4055 ); 4056 4057select_read() does not return anything significant. 4058 4059=head3 select_write FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ] 4060 4061select_write() follows the same semantics as select_read(), but it 4062starts or stops a watcher that looks for write-readiness. That is, 4063when EVENT_NAME is delivered, it means that FILE_HANDLE is ready to be 4064written to. 4065 4066select_write() does not return anything significant. 4067 4068=head3 select_expedite FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ] 4069 4070select_expedite() does the same sort of thing as select_read() and 4071select_write(), but it watches a FILE_HANDLE for out-of-band data 4072ready to be input from a FILE_HANDLE. Hardly anybody uses this, but 4073it exists for completeness' sake. 4074 4075An EVENT_NAME event will be delivered whenever the FILE_HANDLE can be 4076read from out-of-band. Out-of-band data is considered "expedited" 4077because it is often ahead of a socket's normal data. 4078 4079select_expedite() does not return anything significant. 4080 4081=head3 select_pause_read FILE_HANDLE 4082 4083select_pause_read() is a lightweight way to pause a FILE_HANDLE input 4084watcher without performing all the bookkeeping of a select_read(). 4085It's used with select_resume_read() to implement input flow control. 4086 4087Input that occurs on FILE_HANDLE will backlog in the operating system 4088buffers until select_resume_read() is called. 4089 4090A side effect of bypassing the select_read() bookkeeping is that a 4091paused FILE_HANDLE will not prematurely stop the current session. 4092 4093select_pause_read() does not return anything significant. 4094 4095=head3 select_resume_read FILE_HANDLE 4096 4097select_resume_read() resumes a FILE_HANDLE input watcher that was 4098previously paused by select_pause_read(). See select_pause_read() for 4099more discussion on lightweight input flow control. 4100 4101Data backlogged in the operating system due to a select_pause_read() 4102call will become available after select_resume_read() is called. 4103 4104select_resume_read() does not return anything significant. 4105 4106=head3 select_pause_write FILE_HANDLE 4107 4108select_pause_write() pauses a FILE_HANDLE output watcher the same way 4109select_pause_read() does for input. Please see select_pause_read() 4110for further discussion. 4111 4112=head3 select_resume_write FILE_HANDLE 4113 4114select_resume_write() resumes a FILE_HANDLE output watcher the same 4115way that select_resume_read() does for input. See 4116select_resume_read() for further discussion. 4117 4118=head3 select FILE_HANDLE [, EV_READ [, EV_WRITE [, EV_EXPEDITE [, ARGS] ] ] ] 4119 4120POE::Kernel's select() method sets or clears a FILE_HANDLE's read, 4121write and expedite watchers at once. It's a little more expensive 4122than calling select_read(), select_write() and select_expedite() 4123manually, but it's significantly more convenient. 4124 4125Defined event names enable their corresponding watchers, and undefined 4126event names disable them. This turns off all the watchers for a 4127FILE_HANDLE: 4128 4129 sub stop_io { 4130 $_[KERNEL]->select( $_[HEAP]{file_handle} ); 4131 } 4132 4133This statement: 4134 4135 $_[KERNEL]->select( $file_handle, undef, "write_event", undef, @stuff ); 4136 4137is equivalent to: 4138 4139 $_[KERNEL]->select_read( $file_handle ); 4140 $_[KERNEL]->select_write( $file_handle, "write_event", @stuff ); 4141 $_[KERNEL]->select_expedite( $file_handle ); 4142 4143POE::Kernel's select() should not be confused with Perl's built-in 4144select() function. 4145 4146As with the other I/O watcher methods, select() does not return a 4147meaningful value. 4148 4149=head2 Session Management 4150 4151Sessions are dynamic. They may be created and destroyed during a 4152program's lifespan. When a session is created, it becomes the "child" 4153of the current session. The creator -- the current session -- becomes 4154its "parent" session. This is loosely modeled after UNIX processes. 4155 4156The most common session management is done by creating new sessions 4157and allowing them to eventually stop. 4158 4159Every session has a parent, even the very first session created. 4160Sessions without obvious parents are children of the program's 4161POE::Kernel instance. 4162 4163Child sessions will keep their parents active. See L</Session 4164Lifespans> for more about why sessions stay alive. 4165 4166The parent/child relationship tree also governs the way many signals 4167are dispatched. See L</Common Signal Dispatching> for more 4168information on that. 4169 4170=head3 Session Management Events (_start, _stop, _parent, _child) 4171 4172POE::Kernel provides four session management events: _start, _stop, 4173_parent and _child. They are invoked synchronously whenever a session 4174is newly created or just about to be destroyed. 4175 4176=over 2 4177 4178=item _start 4179 4180_start should be familiar by now. POE dispatches the _start event to 4181initialize a session after it has been registered under POE::Kernel. 4182What is not readily apparent, however, is that it is invoked before 4183the L<POE::Session|POE::Session> constructor returns. 4184 4185Within the _start handler, the event's sender is the session that 4186created the new session. Otherwise known as the new session's 4187I<parent>. Sessions created before POE::Kernel->run() is called will 4188be descendents of the program's POE::Kernel singleton. 4189 4190The _start handler's return value is passed to the parent session in a 4191_child event, along with the notification that the parent's new child 4192was created successfully. See the discussion of _child for more 4193details. 4194 4195 POE::Session->create( 4196 inline_states => { _start=> \&_start }, 4197 args => [ $some, $args ] 4198 ); 4199 4200 sub _start { 4201 my ( $some, $args ) = @_[ ARG0, ARG1 ]; 4202 # .... 4203 } 4204 4205=item _stop 4206 4207_stop is a little more mysterious. POE calls a _stop handler when a 4208session is irrevocably about to be destroyed. Part of session 4209destruction is the forcible reclamation of its resources (events, 4210timers, message events, etc.) so it's not possible to post() a message 4211from _stop's handler. A program is free to try, but the event will be 4212destroyed before it has a chance to be dispatched. 4213 4214the _stop handler's return value is passed to the parent's _child 4215event. See _child for more details. 4216 4217_stop is usually invoked when a session has no further reason to live, 4218although signals may cause them to stop sooner. 4219 4220The corresponding _child handler is invoked synchronously just after 4221_stop returns. 4222 4223=item _parent 4224 4225_parent is used to notify a child session when its parent has changed. 4226This usually happens when a session is first created. It can also 4227happen when a child session is detached from its parent. See 4228L<detach_child|/"detach_child CHILD_SESSION"> and L</detach_myself>. 4229 4230_parent's ARG0 contains the session's previous parent, and ARG1 4231contains its new parent. 4232 4233 sub _parent { 4234 my ( $old_parent, $new_parent ) = @_[ ARG0, ARG1 ]; 4235 print( 4236 "Session ", $_[SESSION]->ID, 4237 " parent changed from session ", $old_parent->ID, 4238 " to session ", $new_parent->ID, 4239 "\n" 4240 ); 4241 } 4242 4243=item _child 4244 4245_child notifies one session when a child session has been created, 4246destroyed, or reassigned to or from another parent. It's usually 4247dispatched when sessions are created or destroyed. It can also happen 4248when a session is detached from its parent. 4249 4250_child includes some information in the "arguments" portion of @_. 4251Typically ARG0, ARG1 and ARG2, but these may be overridden by a 4252different POE::Session class: 4253 4254ARG0 contains a string describing what has happened to the child. The 4255string may be 'create' (the child session has been created), 'gain' 4256(the child has been given by another session), or 'lose' (the child 4257session has stopped or been given away). 4258 4259In all cases, ARG1 contains a reference to the child session. 4260 4261In the 'create' case, ARG2 holds the value returned by the child 4262session's _start handler. Likewise, ARG2 holds the _stop handler's 4263return value for the 'lose' case. 4264 4265 sub _child { 4266 my( $reason, $child ) = @_[ ARG0, ARG1 ]; 4267 if( $reason eq 'create' ) { 4268 my $retval = $_[ ARG2 ]; 4269 } 4270 # ... 4271 } 4272 4273=back 4274 4275The events are delivered in specific orders. 4276 4277=head4 When a new session is created: 4278 4279=over 4 4280 4281=item 1 4282 4283The session's constructor is called. 4284 4285=item 2 4286 4287The session is put into play. That is, POE::Kernel 4288enters the session into its bookkeeping. 4289 4290=item 3 4291 4292The new session receives _start. 4293 4294=item 4 4295 4296The parent session receives _child ('create'), the new 4297session reference, and the new session's _start's return value. 4298 4299=item 5 4300 4301The session's constructor returns. 4302 4303=back 4304 4305=head4 When an old session stops: 4306 4307=over 4 4308 4309=item 1 4310 4311If the session has children of its 4312own, they are given to the session's parent. This triggers one or 4313more _child ('gain') events in the parent, and a _parent in each 4314child. 4315 4316=item 2 4317 4318Once divested of its children, the stopping session 4319receives a _stop event. 4320 4321=item 3 4322 4323The stopped session's parent receives a 4324_child ('lose') event with the departing child's reference and _stop 4325handler's return value. 4326 4327=item 4 4328 4329The stopped session is removed from play, 4330as are all its remaining resources. 4331 4332=item 5 4333 4334The parent session is checked 4335for idleness. If so, garbage collection will commence on it, and it 4336too will be stopped 4337 4338=back 4339 4340=head4 When a session is detached from its parent: 4341 4342=over 4 4343 4344=item 1 4345 4346The parent session of 4347the session being detached is notified with a _child ('lose') event. 4348The _stop handler's return value is undef since the child is not 4349actually stopping. 4350 4351=item 2 4352 4353The detached session is notified with a _parent event that its new parent is 4354POE::Kernel itself. 4355 4356=item 3 4357 4358POE::Kernel's bookkeeping data is adjusted to reflect the change of 4359parentage. 4360 4361=item 4 4362 4363The old parent session is checked for idleness. If so, garbage collection 4364will commence on it, and it too will be stopped 4365 4366=back 4367 4368=head3 Session Management Methods 4369 4370These methods allow sessions to be detached from their parents in the 4371rare cases where the parent/child relationship gets in the way. 4372 4373=head4 detach_child CHILD_SESSION 4374 4375detach_child() detaches a particular CHILD_SESSION from the current 4376session. On success, the CHILD_SESSION will become a child of the 4377POE::Kernel instance, and detach_child() will return true. On failure 4378however, detach_child() returns false and sets $! to explain the 4379nature of the failure: 4380 4381=over 4 4382 4383=item ESRCH ("No such process"). 4384 4385The CHILD_SESSION is not a valid session. 4386 4387=item EPERM ("Operation not permitted"). 4388 4389The CHILD_SESSION exists, but it is not a child of the current session. 4390 4391=back 4392 4393detach_child() will generate L</_parent> and/or L</_child> events to the 4394appropriate sessions. See L<Session Management Events|/Session Management> for a detailed 4395explanation of these events. See 4396L<above|/"When a session is detached from its parent:"> 4397for the order the events are generated. 4398 4399=head4 detach_myself 4400 4401detach_myself() detaches the current session from its current parent. 4402The new parent will be the running POE::Kernel instance. It returns 4403true on success. On failure it returns false and sets C<$!> to 4404explain the nature of the failure: 4405 4406=over 4 4407 4408=item EPERM ("Operation not permitted"). 4409 4410The current session is already a 4411child of POE::Kernel, so it may not be detached. 4412 4413=back 4414 4415detach_child() will generate L</_parent> and/or L</_child> events to the 4416appropriate sessions. See L<Session Management Events|/Session Management> for a detailed 4417explanation of these events. See 4418L<above|/"When a session is detached from its parent:"> 4419for the order the events are generated. 4420 4421=head2 Signals 4422 4423POE::Kernel provides methods through which a program can register 4424interest in signals that come along, can deliver its own signals 4425without resorting to system calls, and can indicate that signals have 4426been handled so that default behaviors are not necessary. 4427 4428Signals are I<action at a distance> by nature, and their implementation 4429requires widespread synchronization between sessions (and reentrancy 4430in the dispatcher, but that's an implementation detail). Perfecting 4431the semantics has proven difficult, but POE tries to do the Right 4432Thing whenever possible. 4433 4434POE does not register %SIG handlers for signals until sig() is called 4435to watch for them. Therefore a signal's default behavior occurs for 4436unhandled signals. That is, SIGINT will gracelessly stop a program, 4437SIGWINCH will do nothing, SIGTSTP will pause a program, and so on. 4438 4439=head3 Signal Classes 4440 4441There are three signal classes. Each class defines a default behavior 4442for the signal and whether the default can be overridden. They are: 4443 4444=head4 Benign, advisory, or informative signals 4445 4446These are three names for the same signal class. Signals in this class 4447notify a session of an event but do not terminate the session if they are 4448not handled. 4449 4450It is possible for an application to create its own benign signals. See 4451L</signal> below. 4452 4453=head4 Terminal signals 4454 4455Terminal signals will kill sessions if they are not handled by a 4456L</sig_handled>() call. The OS signals that usually kill or dump a process 4457are considered terminal in POE, but they never trigger a coredump. These 4458are: HUP, INT, QUIT and TERM. 4459 4460There are two terminal signals created by and used within POE: 4461 4462=over 4463 4464=item DIE 4465 4466C<DIE> notifies sessions that a Perl exception has occurred. See 4467L</"Exception Handling"> for details. 4468 4469=item IDLE 4470 4471The C<IDLE> signal is used to notify leftover sessions that a 4472program has run out of things to do. 4473 4474=back 4475 4476=head4 Nonmaskable signals 4477 4478Nonmaskable signals are terminal regardless whether sig_handled() is 4479called. The term comes from "NMI", the non-maskable CPU interrupt 4480usually generated by an unrecoverable hardware exception. 4481 4482Sessions that receive a non-maskable signal will unavoidably stop. POE 4483implements two non-maskable signals: 4484 4485=over 4486 4487=item ZOMBIE 4488 4489This non-maskable signal is fired if a program has received an C<IDLE> signal 4490but neither restarted nor exited. The program has become a zombie (that is, 4491it's neither dead nor alive, and only exists to consume braaaains ...er... 4492memory). The C<ZOMBIE> signal acts like a cricket bat to the head, 4493bringing the zombie down, for good. 4494 4495=item UIDESTROY 4496 4497This non-maskable signal indicates that a program's user 4498interface has been closed, and the program should take the user's hint 4499and buzz off as well. It's usually generated when a particular GUI 4500widget is closed. 4501 4502=back 4503 4504=head3 Common Signal Dispatching 4505 4506Most signals are not dispatched to a single session. POE's session 4507lineage (parents and children) form a sort of family tree. When a 4508signal is sent to a session, it first passes through any children (and 4509grandchildren, and so on) that are also interested in the signal. 4510 4511In the case of terminal signals, if any of the sessions a signal passes 4512through calls L</sig_handled>(), then the signal is considered taken care 4513of. However if none of them do, then the entire session tree rooted at the 4514destination session is terminated. For example, consider this tree of 4515sessions: 4516 4517 POE::Kernel 4518 Session 2 4519 Session 4 4520 Session 5 4521 Session 3 4522 Session 6 4523 Session 7 4524 4525POE::Kernel is the parent of sessions 2 and 3. Session 2 is the 4526parent of sessions 4 and 5. And session 3 is the parent of 6 and 7. 4527 4528A signal sent to Session 2 may also be dispatched to session 4 and 5 4529because they are 2's children. Sessions 4 and 5 will only receive the 4530signal if they have registered the appropriate watcher. If the signal is 4531terminal, and none of the signal watchers in sessions 2, 4 and 5 called 4532C<sig_handled()>, all 3 sessions will be terminated. 4533 4534The program's POE::Kernel instance is considered to be a session for 4535the purpose of signal dispatch. So any signal sent to POE::Kernel 4536will propagate through every interested session in the entire program. 4537This is in fact how OS signals are handled: A global signal handler is 4538registered to forward the signal to POE::Kernel. 4539 4540=head3 Signal Semantics 4541 4542All signals come with the signal name in ARG0. The signal name is as 4543it appears in %SIG, with one exception: Child process signals are 4544always "CHLD" even if the current operating system recognizes them as 4545"CLD". 4546 4547Certain signals have special semantics: 4548 4549=head4 SIGCHLD 4550 4551=head4 SIGCLD 4552 4553Both C<SIGCHLD> and C<SIGCLD> indicate that a child process has exited 4554or been terminated by some signal. The actual signal name varies 4555between operating systems, but POE uses C<CHLD> regardless. 4556 4557Interest in C<SIGCHLD> is registered using the L</sig_child> method. 4558The L</sig>() method also works, but it's not as nice. 4559 4560The C<SIGCHLD> event includes three parameters: 4561 4562=over 4563 4564=item ARG0 4565 4566C<ARG0> contains the string 'CHLD' (even if the OS calls it SIGCLD, 4567SIGMONKEY, or something else). 4568 4569=item ARG1 4570 4571C<ARG1> contains the process ID of the finished child process. 4572 4573=item ARG2 4574 4575And C<ARG2> holds the value of C<$?> for the finished process. 4576 4577=back 4578 4579Example: 4580 4581 sub sig_CHLD { 4582 my( $name, $PID, $exit_val ) = @_[ ARG0, ARG1, ARG2 ]; 4583 # ... 4584 } 4585 4586=head4 SIGPIPE 4587 4588SIGPIPE is rarely used since POE provides events that do the same 4589thing. Nevertheless SIGPIPE is supported if you need it. Unlike most 4590events, however, SIGPIPE is dispatched directly to the active session 4591when it's caught. Barring race conditions, the active session should 4592be the one that caused the OS to send the signal in the first place. 4593 4594The SIGPIPE signal will still propagate to child sessions. 4595 4596ARG0 is "PIPE". There is no other information associated with this 4597signal. 4598 4599=head4 SIGWINCH 4600 4601Window resizes can generate a large number of signals very quickly. 4602This may not be a problem when using perl 5.8.0 or later, but earlier 4603versions may not take kindly to such abuse. You have been warned. 4604 4605ARG0 is "WINCH". There is no other information associated with this 4606signal. 4607 4608=head3 Exception Handling 4609 4610POE::Kernel provides only one form of exception handling: the 4611C<DIE> signal. 4612 4613When exception handling is enabled (the default), POE::Kernel wraps state 4614invocation in C<eval{}>. If the event handler raises an exception, generally 4615with C<die>, POE::Kernel will dispatch a C<DIE> signal to the event's 4616destination session. 4617 4618C<ARG0> is the signal name, C<DIE>. 4619 4620C<ARG1> is a hashref describing the exception: 4621 4622=over 4623 4624=item error_str 4625 4626The text of the exception. In other words, C<$@>. 4627 4628=item dest_session 4629 4630Session object of the state that the raised the exception. In other words, 4631C<$_[SESSION]> in the function that died. 4632 4633=item event 4634 4635Name of the event that died. 4636 4637=item source_session 4638 4639Session object that sent the original event. 4640That is, C<$_[SENDER]> in the function that died. 4641 4642=item from_state 4643 4644State from which the original event was sent. 4645That is, C<$_[CALLER_STATE]> in the function that died. 4646 4647=item file 4648 4649Name of the file the event was sent from. 4650That is, C<$_[CALLER_FILE]> in the function that died. 4651 4652=item line 4653 4654Line number the event was sent from. 4655That is, C<$_[CALLER_LINE]> in the function that died. 4656 4657=back 4658 4659I<Note that the preceding discussion assumes you are using 4660L<POE::Session|POE::Session>'s call semantics.> 4661 4662Note that the C<DIE> signal is sent to the session that raised the 4663exception, not the session that sent the event that caused the exception to 4664be raised. 4665 4666 sub _start { 4667 $poe_kernel->sig( DIE => 'sig_DIE' ); 4668 $poe_kernel->yield( 'some_event' ); 4669 } 4670 4671 sub some_event { 4672 die "I didn't like that!"; 4673 } 4674 4675 sub sig_DIE { 4676 my( $sig, $ex ) = @_[ ARG0, ARG1 ]; 4677 # $sig is 'DIE' 4678 # $ex is the exception hash 4679 warn "$$: error in $ex->{event}: $ex->{error_str}"; 4680 $poe_kernel->sig_handled(); 4681 4682 # Send the signal to session that sent the original event. 4683 if( $ex->{source_session} ne $_[SESSION] ) { 4684 $poe_kernel->signal( $ex->{source_session}, 'DIE', $sig, $ex ); 4685 } 4686 } 4687 4688POE::Kernel's built-in exception handling can be disabled by setting 4689the C<POE::Kernel::CATCH_EXCEPTIONS> constant to zero. As with other 4690compile-time configuration constants, it must be set before 4691POE::Kernel is compiled: 4692 4693 BEGIN { 4694 package POE::Kernel; 4695 use constant CATCH_EXCEPTIONS => 0; 4696 } 4697 use POE; 4698 4699or 4700 4701 sub POE::Kernel::CATCH_EXCEPTIONS () { 0 } 4702 use POE; 4703 4704=head2 Signal Watcher Methods 4705 4706And finally the methods themselves. 4707 4708=head3 sig SIGNAL_NAME [, EVENT_NAME [, LIST] ] 4709 4710sig() registers or unregisters an EVENT_NAME event for a particular 4711SIGNAL_NAME, with an optional LIST of parameters that will be passed 4712to the signal's handler---after any data that comes wit the signal. 4713 4714If EVENT_NAME is defined, the signal handler is registered. Otherwise 4715it's unregistered. 4716 4717Each session can register only one handler per SIGNAL_NAME. 4718Subsequent registrations will replace previous ones. Multiple 4719sessions may however watch the same signal. 4720 4721SIGNAL_NAMEs are generally the same as members of C<%SIG>, with two 4722exceptions. First, C<CLD> is an alias for C<CHLD> (although see 4723L</sig_child>). And second, it's possible to send and handle signals 4724created by the application and have no basis in the operating system. 4725 4726 sub handle_start { 4727 $_[KERNEL]->sig( INT => "event_ui_shutdown" ); 4728 $_[KERNEL]->sig( bat => "holy_searchlight_batman" ); 4729 $_[KERNEL]->sig( signal => "main_screen_turn_on" ); 4730 } 4731 4732The operating system may never be able to generate the last two 4733signals, but a POE session can by using POE::Kernel's 4734L</signal>() method. 4735 4736Later on the session may decide not to handle the signals: 4737 4738 sub handle_ui_shutdown { 4739 $_[KERNEL]->sig( "INT" ); 4740 $_[KERNEL]->sig( "bat" ); 4741 $_[KERNEL]->sig( "signal" ); 4742 } 4743 4744More than one session may register interest in the same signal, and a 4745session may clear its own signal watchers without affecting those in 4746other sessions. 4747 4748sig() does not return a meaningful value. 4749 4750=head3 sig_child PROCESS_ID [, EVENT_NAME [, LIST] ] 4751 4752sig_child() is a convenient way to deliver an EVENT_NAME event when a 4753particular PROCESS_ID has exited. An optional LIST of parameters will 4754be passed to the signal handler after the waitpid() information. 4755 4756The watcher can be cleared at any time by calling sig_child() with 4757just the PROCESS_ID. 4758 4759A session may register as many sig_child() handlers as necessary, but 4760a session may only have one per PROCESS_ID. 4761 4762sig_child() watchers are one-shot. They automatically unregister 4763themselves once the EVENT_NAME has been delivered. There's no point 4764in continuing to watch for a signal that will never come again. Other 4765signal handlers persist until they are cleared. 4766 4767sig_child() watchers keep a session alive for as long as they are 4768active. This is unique among POE's signal watchers. 4769 4770Programs that wish to reliably reap child processes should be sure to 4771call sig_child() before returning from the event handler that forked 4772the process. Otherwise POE::Kernel may have an opportunity to call 4773waitpid() before an appropriate event watcher has been registered. 4774 4775Programs that reap processes with waitpid() must clear POE's watchers 4776for the same process IDs, otherwise POE will wait indefinitely for 4777processes that never send signals. 4778 4779sig_child() does not return a meaningful value. 4780 4781 sub forked_parent { 4782 my( $heap, $pid, $details ) = @_[ HEAP, ARG0, ARG1 ]; 4783 $poe_kernel->sig_child( $pid, 'sig_child', $details ); 4784 } 4785 4786 sub sig_child { 4787 my( $heap, $sig, $pid, $exit_val, $details ) = @_[ HEAP, ARG0..ARG3 ]; 4788 my $details = delete $heap->{ $pid }; 4789 warn "$$: Child $pid exited" 4790 # .... also, $details has been passed from forked_parent() 4791 # through sig_child() 4792 } 4793 4794=head3 sig_handled 4795 4796sig_handled() informs POE::Kernel that the currently dispatched signal has 4797been handled by the currently active session. If the signal is terminal, the 4798sig_handled() call prevents POE::Kernel from stopping the sessions that 4799received the signal. 4800 4801A single signal may be dispatched to several sessions. Only one needs 4802to call sig_handled() to prevent the entire group from being stopped. 4803If none of them call it, however, then they are all stopped together. 4804 4805sig_handled() does not return a meaningful value. 4806 4807 sub _start { 4808 $_[KERNEL]->sig( INT => 'sig_INT' ); 4809 } 4810 4811 sub sig_INT { 4812 warn "$$ SIGINT"; 4813 $_[KERNEL]->sig_handled(); 4814 } 4815 4816=head3 signal SESSION, SIGNAL_NAME [, ARGS_LIST] 4817 4818signal() posts a SIGNAL_NAME signal to a specific SESSION with an 4819optional ARGS_LIST that will be passed to every interested handler. As 4820mentioned elsewhere, the signal may be delivered to SESSION's 4821children, grandchildren, and so on. And if SESSION is the POE::Kernel 4822itself, then all interested sessions will receive the signal. 4823 4824It is possible to send a signal in POE that doesn't exist in the 4825operating system. signal() places the signal directly into POE's 4826event queue as if they came from the operating system, but they are 4827not limited to signals recognized by kill(). POE uses a few of these 4828fictitious signals for its own global notifications. 4829 4830For example: 4831 4832 sub some_event_handler { 4833 # Turn on all main screens. 4834 $_[KERNEL]->signal( $_[KERNEL], "signal" ); 4835 } 4836 4837signal() returns true on success. On failure, it returns false after 4838setting $! to explain the nature of the failure: 4839 4840=over 4841 4842=item ESRCH ("No such process") 4843 4844The SESSION does not exist. 4845 4846=back 4847 4848Because all sessions are a child of POE::Kernel, sending a signal to 4849the kernel will propagate the signal to all sessions. This is a cheap 4850form of I<multicast>. 4851 4852 $_[KERNEL]->signal( $_[KERNEL], 'shutdown' ); 4853 4854=head3 signal_ui_destroy WIDGET_OBJECT 4855 4856signal_ui_destroy() associates the destruction of a particular 4857WIDGET_OBJECT with the complete destruction of the program's user 4858interface. When the WIDGET_OBJECT destructs, POE::Kernel issues the 4859non-maskable UIDESTROY signal, which quickly triggers mass destruction 4860of all active sessions. POE::Kernel->run() returns shortly 4861thereafter. 4862 4863 sub setup_ui { 4864 $_[HEAP]{main_widget} = Gtk->new("toplevel"); 4865 # ... populate the main widget here ... 4866 $_[KERNEL]->signal_ui_destroy( $_[HEAP]{main_widget} ); 4867 } 4868 4869Detecting widget destruction is specific to each toolkit. 4870 4871=head2 Event Handler Management 4872 4873Event handler management methods let sessions hot swap their event 4874handlers at run time. For example, the L<POE::Wheel|POE::Wheel> 4875objects use state() to dynamically mix their own event handlers into 4876the sessions that create them. 4877 4878These methods only affect the current session; it would be rude to 4879change another session's handlers. 4880 4881There is only one method in this group. Since it may be called in 4882several different ways, it may be easier to understand if each is 4883documented separately. 4884 4885=head3 state EVENT_NAME [, CODE_REFERNCE] 4886 4887state() sets or removes a handler for EVENT_NAME in the current 4888session. The function referred to by CODE_REFERENCE will be called 4889whenever EVENT_NAME events are dispatched to the current session. If 4890CODE_REFERENCE is omitted, the handler for EVENT_NAME will be removed. 4891 4892A session may only have one handler for a given EVENT_NAME. 4893Subsequent attempts to set an EVENT_NAME handler will replace earlier 4894handlers with the same name. 4895 4896 # Stop paying attention to input. Say goodbye, and 4897 # trigger a socket close when the message is sent. 4898 sub send_final_response { 4899 $_[HEAP]{wheel}->put("KTHXBYE"); 4900 $_[KERNEL]->state( 'on_client_input' ); 4901 $_[KERNEL]->state( on_flush => \&close_connection ); 4902 } 4903 4904=head3 state EVENT_NAME [, OBJECT_REFERENCE [, OBJECT_METHOD_NAME] ] 4905 4906Set or remove a handler for EVENT_NAME in the current session. If an 4907OBJECT_REFERENCE is given, that object will handle the event. An 4908optional OBJECT_METHOD_NAME may be provided. If the method name is 4909not given, POE will look for a method matching the EVENT_NAME instead. 4910If the OBJECT_REFERENCE is omitted, the handler for EVENT_NAME will be 4911removed. 4912 4913A session may only have one handler for a given EVENT_NAME. 4914Subsequent attempts to set an EVENT_NAME handler will replace earlier 4915handlers with the same name. 4916 4917 $_[KERNEL]->state( 'some_event', $self ); 4918 $_[KERNEL]->state( 'other_event', $self, 'other_method' ); 4919 4920=head3 state EVENT_NAME [, CLASS_NAME [, CLASS_METHOD_NAME] ] 4921 4922This form of state() call is virtually identical to that of the object 4923form. 4924 4925Set or remove a handler for EVENT_NAME in the current session. If an 4926CLASS_NAME is given, that class will handle the event. An optional 4927CLASS_METHOD_NAME may be provided. If the method name is not given, 4928POE will look for a method matching the EVENT_NAME instead. If the 4929CLASS_NAME is omitted, the handler for EVENT_NAME will be removed. 4930 4931A session may only have one handler for a given EVENT_NAME. 4932Subsequent attempts to set an EVENT_NAME handler will replace earlier 4933handlers with the same name. 4934 4935 $_[KERNEL]->state( 'some_event', __PACKAGE__ ); 4936 $_[KERNEL]->state( 'other_event', __PACKAGE__, 'other_method' ); 4937 4938=head2 Public Reference Counters 4939 4940The methods in this section manipulate reference counters on the 4941current session or another session. 4942 4943Each session has a namespace for user-manipulated reference counters. 4944These namespaces are associated with the target SESSION_ID for the 4945reference counter methods, not the caller. Nothing currently prevents 4946one session from decrementing a reference counter that was incremented 4947by another, but this behavior is not guaranteed to remain. For now, 4948it's up to the users of these methods to choose obscure counter names 4949to avoid conflicts. 4950 4951Reference counting is a big part of POE's magic. Various objects 4952(mainly event watchers and components) hold references to the sessions 4953that own them. L</Session Lifespans> explains the concept in more 4954detail. 4955 4956The ability to keep a session alive is sometimes useful in an application or 4957library. For example, a component may hold a public reference to another 4958session while it processes a request from that session. In doing so, the 4959component guarantees that the requester is still around when a response is 4960eventually ready. Keeping a reference to the session's object is not 4961enough. POE::Kernel has its own internal reference counting mechanism. 4962 4963=head3 refcount_increment SESSION_ID, COUNTER_NAME 4964 4965refcount_increment() increases the value of the COUNTER_NAME reference 4966counter for the session identified by a SESSION_ID. To discourage the 4967use of session references, the refcount_increment() target session 4968must be specified by its session ID. 4969 4970The target session will not stop until the value of any and all of its 4971COUNTER_NAME reference counters are zero. (Actually, it may stop in 4972some cases, such as failing to handle a terminal signal.) 4973 4974Negative reference counters are legal. They still must be incremented 4975back to zero before a session is eligible for stopping. 4976 4977 sub handle_request { 4978 # Among other things, hold a reference count on the sender. 4979 $_[KERNEL]->refcount_increment( $_[SENDER]->ID, "pending request"); 4980 $_[HEAP]{requesters}{$request_id} = $_[SENDER]->ID; 4981 } 4982 4983For this to work, the session needs a way to remember the 4984$_[SENDER]->ID for a given request. Customarily the session generates 4985a request ID and uses that to track the request until it is fulfilled. 4986 4987refcount_increment() returns the resulting reference count (which may 4988be zero) on success. On failure, it returns undef and sets $! to be 4989the reason for the error. 4990 4991ESRCH: The SESSION_ID does not refer to a currently active session. 4992 4993=head3 refcount_decrement SESSION_ID, COUNTER_NAME 4994 4995refcount_decrement() reduces the value of the COUNTER_NAME reference 4996counter for the session identified by a SESSION_ID. It is the 4997counterpoint for refcount_increment(). Please see 4998refcount_increment() for more context. 4999 5000 sub finally_send_response { 5001 # Among other things, release the reference count for the 5002 # requester. 5003 my $requester_id = delete $_[HEAP]{requesters}{$request_id}; 5004 $_[KERNEL]->refcount_decrement( $requester_id, "pending request"); 5005 } 5006 5007The requester's $_[SENDER]->ID is remembered and removed from the heap 5008(lest there be memory leaks). It's used to decrement the reference 5009counter that was incremented at the start of the request. 5010 5011refcount_decrement() returns the resulting reference count (which may 5012be zero) on success. On failure, it returns undef, and $! will be set 5013to the reason for the failure: 5014 5015ESRCH: The SESSION_ID does not refer to a currently active session. 5016 5017It is not possible to discover currently active public references. See 5018L<POE::API::Peek>. 5019 5020=head2 Kernel State Accessors 5021 5022POE::Kernel provides a few accessors into its massive brain so that 5023library developers may have convenient access to necessary data 5024without relying on their callers to provide it. 5025 5026These accessors expose ways to break session encapsulation. Please 5027use them sparingly and carefully. 5028 5029=head3 get_active_session 5030 5031get_active_session() returns a reference to the session that is 5032currently running, or a reference to the program's POE::Kernel 5033instance if no session is running at that moment. The value is 5034equivalent to L<POE::Session|POE::Session>'s C<$_[SESSION]>. 5035 5036This method was added for libraries that need C<$_[SESSION]> but don't 5037want to include it as a parameter in their APIs. 5038 5039 sub some_housekeeping { 5040 my( $self ) = @_; 5041 my $session = $poe_kernel->get_active_session; 5042 # do some housekeeping on $session 5043 } 5044 5045=head3 get_active_event 5046 5047get_active_event() returns the name of the event currently being 5048dispatched. It returns an empty string when called outside event 5049dispatch. The value is equivalent to L<POE::Session|POE::Session>'s 5050C<$_[STATE]>. 5051 5052 sub waypoint { 5053 my( $message ) = @_; 5054 my $event = $poe_kernel->get_active_event; 5055 print STDERR "$$:$event:$mesage\n"; 5056 } 5057 5058=head3 get_event_count 5059 5060get_event_count() returns the number of events pending in POE's event 5061queue. It is exposed for L<POE::Loop|POE::Loop> class authors. It 5062may be deprecated in the future. 5063 5064=head3 get_next_event_time 5065 5066get_next_event_time() returns the time the next event is due, in a 5067form compatible with the UNIX time() function. It is exposed for 5068L<POE::Loop|POE::Loop> class authors. It may be deprecated in the future. 5069 5070=head3 poe_kernel_loop 5071 5072poe_kernel_loop() returns the name of the POE::Loop class that is used 5073to detect and dispatch events. 5074 5075=head2 Session Helper Methods 5076 5077The methods in this group expose features for L<POE::Session|POE::Session> 5078class authors. 5079 5080=head3 session_alloc SESSION_OBJECT [, START_ARGS] 5081 5082session_alloc() allocates a session context within POE::Kernel for a 5083newly created SESSION_OBJECT. A list of optional START_ARGS will be 5084passed to the session as part of the L</_start> event. 5085 5086The SESSION_OBJECT is expected to follow a subset of POE::Session's 5087interface. 5088 5089There is no session_free(). POE::Kernel determines when the session 5090should stop and performs the necessary cleanup after dispatching _stop 5091to the session. 5092 5093=head2 Miscellaneous Methods 5094 5095We don't know where to classify the methods in this section. 5096 5097=head3 new 5098 5099It is not necessary to call POE::Kernel's new() method. Doing so will 5100return the program's singleton POE::Kernel object, however. 5101 5102=head1 PUBLIC EXPORTED VARIABLES 5103 5104POE::Kernel exports two variables for your coding enjoyment: 5105C<$poe_kernel> and C<$poe_main_window>. POE::Kernel is implicitly 5106used by POE itself, so using POE gets you POE::Kernel (and its 5107exports) for free. 5108 5109In more detail: 5110 5111=head2 $poe_kernel 5112 5113C<$poe_kernel> contains a reference to the process' POE::Kernel singleton 5114instance. It's mainly used for accessing POE::Kernel methods from places 5115where C<$_[KERNEL]> is not available. It's most commonly used in helper 5116libraries. 5117 5118=head2 $poe_main_window 5119 5120$poe_main_window is used by graphical toolkits that require at least 5121one widget to be created before their event loops are usable. This is 5122currently only Tk. 5123 5124L<POE::Loop::Tk|POE::Loop::Tk> creates a main window to satisfy Tk's 5125event loop. The window is given to the application since POE has no 5126other use for it. 5127 5128C<$poe_main_window> is undefined in toolkits that don't require a 5129widget to dispatch events. 5130 5131On a related note, POE will shut down if the widget in 5132C<$poe_main_window> is destroyed. This can be changed with 5133POE::Kernel's L</signal_ui_destroy> method. 5134 5135=head1 DEBUGGING POE AND PROGRAMS USING IT 5136 5137POE includes quite a lot of debugging code, in the form of both fatal 5138assertions and run-time traces. They may be enabled at compile time, 5139but there is no way to toggle them at run-time. This was done to 5140avoid run-time penalties in programs where debugging is not necessary. 5141That is, in most production cases. 5142 5143Traces are verbose reminders of what's going on within POE. Each is 5144prefixed with a four-character field describing the POE subsystem that 5145generated it. 5146 5147Assertions (asserts) are quiet but deadly, both in performance (they 5148cause a significant run-time performance hit) and because they cause 5149fatal errors when triggered. 5150 5151The assertions and traces are useful for developing programs with POE, 5152but they were originally added to debug POE itself. 5153 5154Each assertion and tracing group is enabled by setting a constant in 5155the POE::Kernel namespace to a true value. 5156 5157 BEGIN { 5158 package POE::Kernel; 5159 use constant ASSERT_DEFAULT => 1; 5160 } 5161 use POE; 5162 5163Or the old-fashioned (and more concise) "constant subroutine" method. 5164This doesn't need the C<BEGIN{}> block since subroutine definitions are 5165done at compile time. 5166 5167 sub POE::Kernel::ASSERT_DEFAULT () { 1 } 5168 use POE; 5169 5170The switches must be defined as constants before POE::Kernel is first 5171loaded. Otherwise Perl's compiler will not see the constants when first 5172compiling POE::Kernel, and the features will not be properly enabled. 5173 5174Assertions and traces may also be enabled by setting shell environment 5175variables. The environment variables are named after the POE::Kernel 5176constants with a "POE_" prefix. 5177 5178 POE_ASSERT_DEFAULT=1 POE_TRACE_DEFAULT=1 ./my_poe_program 5179 5180In alphabetical order: 5181 5182=head2 ASSERT_DATA 5183 5184ASSERT_DATA enables run-time data integrity checks within POE::Kernel 5185and the classes that mix into it. POE::Kernel tracks a lot of 5186cross-referenced data, and this group of assertions ensures that it's 5187consistent. 5188 5189Prefix: <dt> 5190 5191Environment variable: POE_ASSERT_DATA 5192 5193=head2 ASSERT_DEFAULT 5194 5195ASSERT_DEFAULT specifies the default value for assertions that are not 5196explicitly enabled or disabled. This is a quick and reliable way to 5197make sure all assertions are on. 5198 5199No assertion uses ASSERT_DEFAULT directly, and this assertion flag has 5200no corresponding output prefix. 5201 5202Turn on all assertions except ASSERT_EVENTS: 5203 5204 sub POE::Kernel::ASSERT_DEFAULT () { 1 } 5205 sub POE::Kernel::ASSERT_EVENTS () { 0 } 5206 use POE::Kernel; 5207 5208Prefix: (none) 5209 5210Environment variable: POE_ASSERT_DEFAULT 5211 5212=head2 ASSERT_EVENTS 5213 5214ASSERT_EVENTS mainly checks for attempts to dispatch events to 5215sessions that don't exist. This assertion can assist in the debugging 5216of strange, silent cases where event handlers are not called. 5217 5218Prefix: <ev> 5219 5220Environment variable: POE_ASSERT_EVENTS 5221 5222=head2 ASSERT_FILES 5223 5224ASSERT_FILES enables some run-time checks in POE's filehandle watchers 5225and the code that manages them. 5226 5227Prefix: <fh> 5228 5229Environment variable: POE_ASSERT_FILES 5230 5231=head2 ASSERT_RETVALS 5232 5233ASSERT_RETVALS upgrades failure codes from POE::Kernel's methods from 5234advisory return values to fatal errors. Most programmers don't check 5235the values these methods return, so ASSERT_RETVALS is a quick way to 5236validate one's assumption that all is correct. 5237 5238Prefix: <rv> 5239 5240Environment variable: POE_ASSERT_RETVALS 5241 5242=head2 ASSERT_USAGE 5243 5244ASSERT_USAGE is the counterpoint to ASSERT_RETVALS. It enables 5245run-time checks that the parameters to POE::Kernel's methods are 5246correct. It's a quick (but not foolproof) way to verify a program's 5247use of POE. 5248 5249Prefix: <us> 5250 5251Environment variable: POE_ASSERT_USAGE 5252 5253=head2 TRACE_DEFAULT 5254 5255TRACE_DEFAULT specifies the default value for traces that are not 5256explicitly enabled or disabled. This is a quick and reliable way to 5257ensure your program generates copious output on the file named in 5258TRACE_FILENAME or STDERR by default. 5259 5260To enable all traces except a few noisier ones: 5261 5262 sub POE::Kernel::TRACE_DEFAULT () { 1 } 5263 sub POE::Kernel::TRACE_EVENTS () { 0 } 5264 use POE::Kernel; 5265 5266Prefix: (none) 5267 5268Environment variable: POE_TRACE_DEFAULT 5269 5270=head2 TRACE_DESTROY 5271 5272TRACE_DESTROY causes every POE::Session object to dump the contents of 5273its C<$_[HEAP]> when Perl destroys it. This trace was added to help 5274developers find memory leaks in their programs. 5275 5276Prefix: A line that reads "----- Session $self Leak Check -----". 5277 5278Environment variable: POE_TRACE_DESTROY 5279 5280=head2 TRACE_EVENTS 5281 5282TRACE_EVENTS enables messages pertaining to POE's event queue's 5283activities: when events are enqueued, dispatched or discarded, and 5284more. It's great for determining where events go and when. 5285Understandably this is one of POE's more verbose traces. 5286 5287Prefix: <ev> 5288 5289Environment variable: POE_TRACE_EVENTS 5290 5291=head2 TRACE_FILENAME 5292 5293TRACE_FILENAME specifies the name of a file where POE's tracing and 5294assertion messages should go. It's useful if you want the messages 5295but have other plans for STDERR, which is where the messages go by 5296default. 5297 5298POE's tests use this so the trace and assertion code can be 5299instrumented during testing without spewing all over the terminal. 5300 5301Prefix: (none) 5302 5303Environment variable: POE_TRACE_FILENAME 5304 5305=head2 TRACE_FILES 5306 5307TRACE_FILES enables or disables traces in POE's filehandle watchers and 5308the L<POE::Loop|POE::Loop> class that implements the lowest-level filehandle 5309multiplexing. This may be useful when tracking down strange behavior 5310related to filehandles. 5311 5312Prefix: <fh> 5313 5314Environment variable: POE_TRACE_FILES 5315 5316=head2 TRACE_REFCNT 5317 5318TRACE_REFCNT governs whether POE::Kernel will trace sessions' 5319reference counts. As discussed in L</"Session Lifespans">, POE does a 5320lot of reference counting, and the current state of a session's 5321reference counts determines whether the session lives or dies. It's 5322common for developers to wonder why a session stops too early or 5323remains active too long. TRACE_REFCNT can help explain why. 5324 5325Prefix: <rc> 5326 5327Environment variable: POE_TRACE_REFCNT 5328 5329=head2 TRACE_RETVALS 5330 5331TRACE_RETVALS can enable carping whenever a POE::Kernel method is 5332about to fail. It's a non-fatal but noisier form of 5333ASSERT_RETVALS. 5334 5335Prefix: <rv> 5336 5337Environment variable: POE_TRACE_RETVALS 5338 5339=head2 TRACE_SESSIONS 5340 5341TRACE_SESSIONS enables trace messages that pertain to session 5342management. Notice will be given when sessions are created or 5343destroyed, and when the parent or child status of a session changes. 5344 5345Prefix: <ss> 5346 5347Environment variable: POE_TRACE_SESSIONS 5348 5349=head2 TRACE_SIGNALS 5350 5351TRACE_SIGNALS turns on (or off) traces in POE's signal handling 5352subsystem. Signal dispatch is one of POE's more complex parts, and 5353the trace messages may help application developers understand signal 5354propagation and timing. 5355 5356Prefix: <sg> 5357 5358Environment variable: POE_TRACE_SIGNALS 5359 5360=head2 USE_SIGCHLD 5361 5362Whether to use C<$SIG{CHLD}> or to poll at an interval. 5363 5364This flag is enabled by default on Perl >= 5.8.1 as it has support 5365for "safe signals". Please see L<perlipc> for the gory details. 5366 5367You might want to disable this if you are running a version of Perl that 5368is known to have bad signal handling, or if anything hijacks C<$SIG{CHLD}>. 5369One module that is known to do this is L<Apache>. 5370 5371Enabling this flag will cause child reaping to happen almost 5372immediately, as opposed to once per L</CHILD_POLLING_INTERVAL>. 5373 5374=head2 CHILD_POLLING_INTERVAL 5375 5376The interval at which C<wait> is called to determine if child 5377processes need to be reaped and the C<CHLD> signal emulated. 5378 5379Defaults to 1 second. 5380 5381=head2 USE_SIGNAL_PIPE 5382 5383The only safe way to handle signals is to implement a shared-nothing 5384model. POE builds a I<signal pipe> that communicates between the 5385signal handlers and the POE kernel loop in a safe and atomic manner. 5386The signal pipe is implemented with L<POE::Pipe::OneWay>, using a 5387C<pipe> conduit on Unix. Unfortunately, the signal pipe is not compatible 5388with Windows and is not used on that platform. 5389 5390If you wish to revert to the previous unsafe signal behaviour, you 5391must set C<USE_SIGNAL_PIPE> to 0, or the environment variable 5392C<POE_USE_SIGNAL_PIPE>. 5393 5394=head2 CATCH_EXCEPTIONS 5395 5396Whether or not POE should run event handler code in an eval { } and 5397deliver the C<DIE> signal on errors. 5398 5399See L</"Exception Handling">. 5400 5401=head1 ENVIRONMENT VARIABLES FOR TESTING 5402 5403POE's tests are lovely, dark and deep. These environment variables 5404allow testers to take roads less traveled. 5405 5406=head2 POE_DANTIC 5407 5408Windows and Perls built for it tend to be poor at doing UNIXy things, 5409although they do try. POE being very UNIXy itself must skip a lot of 5410Windows tests. The POE_DANTIC environment variable will, when true, 5411enable all these tests. It's intended to be used from time to time to 5412see whether Windows has improved in some area. 5413 5414=head1 SEE ALSO 5415 5416The SEE ALSO section in L<POE> contains a table of contents covering 5417the entire POE distribution. 5418 5419=head1 BUGS 5420 5421=over 5422 5423=item * 5424 5425There is no mechanism in place to prevent external reference count 5426names from clashing. 5427 5428=item * 5429 5430There is no mechanism to catch exceptions generated in another session. 5431 5432=back 5433 5434=head1 AUTHORS & COPYRIGHTS 5435 5436Please see L<POE> for more information about authors and contributors. 5437 5438=cut 5439 5440# rocco // vim: ts=2 sw=2 expandtab 5441# TODO - More practical examples. 5442# TODO - Test the examples. 5443# TODO - Edit. 5444