home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / Kernel.pm < prev    next >
Encoding:
Perl POD Document  |  2004-06-03  |  121.1 KB  |  3,859 lines

  1. # $Id: Kernel.pm,v 1.286 2004/06/02 03:36:53 rcaputo Exp $
  2.  
  3. package POE::Kernel;
  4.  
  5. use strict;
  6.  
  7. use vars qw($VERSION);
  8. $VERSION = do {my@r=(q$Revision: 1.286 $=~/\d+/g);sprintf"%d."."%04d"x$#r,@r};
  9.  
  10. use POE::Queue::Array;
  11. use POSIX qw(fcntl_h sys_wait_h);
  12. use Errno qw(ESRCH EINTR ECHILD EPERM EINVAL EEXIST EAGAIN EWOULDBLOCK);
  13. use Carp qw(carp croak confess cluck);
  14. use Sys::Hostname qw(hostname);
  15. use IO::Handle;
  16.  
  17. # People expect these to be lexical.
  18.  
  19. use vars qw($poe_kernel $poe_main_window);
  20.  
  21. #------------------------------------------------------------------------------
  22. # A cheezy exporter to avoid using Exporter.
  23.  
  24. sub import {
  25.   my $package = caller();
  26.   no strict 'refs';
  27.   *{ $package . '::poe_kernel'      } = \$poe_kernel;
  28.   *{ $package . '::poe_main_window' } = \$poe_main_window;
  29. }
  30.  
  31. #------------------------------------------------------------------------------
  32. # Perform some optional setup.
  33.  
  34. sub RUNNING_IN_HELL () { $^O eq 'MSWin32' }
  35.  
  36. BEGIN {
  37.   local $SIG{'__DIE__'} = 'DEFAULT';
  38.  
  39.   # POE runs better with Time::HiRes, but it also runs without it.
  40.   { no strict 'refs';
  41.  
  42.     # Allow users to turn off Time::HiRes usage for whatever reason.
  43.     my $time_hires_default = 1;
  44.     $time_hires_default = $ENV{USE_TIME_HIRES} if defined $ENV{USE_TIME_HIRES};
  45.     if (defined &USE_TIME_HIRES) {
  46.       $time_hires_default = USE_TIME_HIRES();
  47.     }
  48.     else {
  49.       eval "sub USE_TIME_HIRES () { $time_hires_default }";
  50.     }
  51.   }
  52.   eval {
  53.     require Time::HiRes;
  54.     Time::HiRes->import(qw(time sleep));
  55.   } if USE_TIME_HIRES();
  56.  
  57.   # Provide dummy constants so things at least compile.
  58.  
  59.   if (RUNNING_IN_HELL) {
  60.     eval '*F_GETFL = sub { 0 };';
  61.     eval '*F_SETFL = sub { 0 };';
  62.   }
  63. }
  64.  
  65. #==============================================================================
  66. # Globals, or at least package-scoped things.  Data structurse were
  67. # moved into lexicals in 0.1201.
  68.  
  69. # A flag determining whether there are child processes.  Starts true
  70. # so our waitpid() loop can run at least once.  Starts false when
  71. # running in an Apache handler so our SIGCHLD hijinx don't interfere
  72. # with the web server.
  73. my $kr_child_procs = exists($INC{'Apache.pm'}) ? 0 : 1;
  74.  
  75. # A reference to the currently active session.  Used throughout the
  76. # functions that act on the current session.
  77. my $kr_active_session;
  78. my $kr_active_event;
  79.  
  80. # The Kernel's master queue.
  81. my $kr_queue;
  82.  
  83. # Filehandle activity modes.  They are often used as list indexes.
  84. sub MODE_RD () { 0 }  # read
  85. sub MODE_WR () { 1 }  # write
  86. sub MODE_EX () { 2 }  # exception/expedite
  87.  
  88. #------------------------------------------------------------------------------
  89. # Kernel structure.  This is the root of a large data tree.  Dumping
  90. # $poe_kernel with Data::Dumper or something will show most of the
  91. # data that POE keeps track of.  The exceptions to this are private
  92. # storage in some of the leaf objects, such as POE::Wheel.  All its
  93. # members are described in detail further on.
  94.  
  95. sub KR_SESSIONS       () {  0 } # [ \%kr_sessions,
  96. sub KR_FILENOS        () {  1 } #   \%kr_filenos,
  97. sub KR_SIGNALS        () {  2 } #   \%kr_signals,
  98. sub KR_ALIASES        () {  3 } #   \%kr_aliases,
  99. sub KR_ACTIVE_SESSION () {  4 } #   \$kr_active_session,
  100. sub KR_QUEUE          () {  5 } #   \$kr_queue,
  101. sub KR_ID             () {  6 } #   $unique_kernel_id,
  102. sub KR_SESSION_IDS    () {  7 } #   \%kr_session_ids,
  103. sub KR_SID_SEQ        () {  8 } #   \$kr_sid_seq,
  104. sub KR_EXTRA_REFS     () {  9 } #   \$kr_extra_refs,
  105. sub KR_SIZE           () { 10 } #   XXX UNUSED ???
  106. sub KR_RUN            () { 11 } #   \$kr_run_warning
  107. sub KR_ACTIVE_EVENT   () { 12 } #   \$kr_active_event
  108.                                 # ]
  109.  
  110. # This flag indicates that POE::Kernel's run() method was called.
  111. # It's used to warn about forgetting $poe_kernel->run().
  112.  
  113. sub KR_RUN_CALLED  () { 0x01 }  # $kernel->run() called
  114. sub KR_RUN_SESSION () { 0x02 }  # sessions created
  115. sub KR_RUN_DONE    () { 0x04 }  # run returned
  116. my $kr_run_warning = 0;
  117.  
  118. #------------------------------------------------------------------------------
  119. # Events themselves.
  120.  
  121. sub EV_SESSION    () { 0 }  # [ $destination_session,
  122. sub EV_SOURCE     () { 1 }  #   $sender_session,
  123. sub EV_NAME       () { 2 }  #   $event_name,
  124. sub EV_TYPE       () { 3 }  #   $event_type,
  125. sub EV_ARGS       () { 4 }  #   \@event_parameters_arg0_etc,
  126.                             #
  127.                             #   (These fields go towards the end
  128.                             #   because they are optional in some
  129.                             #   cases.  TODO: Is this still true?)
  130.                             #
  131. sub EV_OWNER_FILE () { 5 }  #   $caller_filename_where_enqueued,
  132. sub EV_OWNER_LINE () { 6 }  #   $caller_line_where_enqueued,
  133.                             # ]
  134.  
  135. sub EV_TIME       () { 7 }  # Maintained by POE::Queue
  136. sub EV_SEQ        () { 8 }  # Maintained by POE::Queue
  137.  
  138. # These are the names of POE's internal events.  They're in constants
  139. # so we don't mistype them again.
  140.  
  141. sub EN_CHILD  () { '_child'           }
  142. sub EN_GC     () { '_garbage_collect' }
  143. sub EN_PARENT () { '_parent'          }
  144. sub EN_SCPOLL () { '_sigchld_poll'    }
  145. sub EN_SIGNAL () { '_signal'          }
  146. sub EN_START  () { '_start'           }
  147. sub EN_STOP   () { '_stop'            }
  148. sub EN_STAT   () { '_stat_tick'       }
  149.  
  150. # These are POE's event classes (types).  They often shadow the event
  151. # names themselves, but they can encompass a large group of events.
  152. # For example, ET_ALARM describes anything enqueued as by an alarm
  153. # call.  Types are preferred over names because bitmask tests are
  154. # faster than sring equality tests.
  155.  
  156. sub ET_POST   () { 0x0001 }  # User events (posted, yielded).
  157. sub ET_CALL   () { 0x0002 }  # User events that weren't enqueued.
  158. sub ET_START  () { 0x0004 }  # _start
  159. sub ET_STOP   () { 0x0008 }  # _stop
  160. sub ET_SIGNAL () { 0x0010 }  # _signal
  161. sub ET_GC     () { 0x0020 }  # _garbage_collect
  162. sub ET_PARENT () { 0x0040 }  # _parent
  163. sub ET_CHILD  () { 0x0080 }  # _child
  164. sub ET_SCPOLL () { 0x0100 }  # _sigchild_poll
  165. sub ET_ALARM  () { 0x0200 }  # Alarm events.
  166. sub ET_SELECT () { 0x0400 }  # File activity events.
  167. sub ET_STAT   () { 0x0800 }  # Statistics gathering
  168.  
  169. # A mask for all events generated by/for users.
  170. sub ET_MASK_USER () { ~(ET_GC | ET_SCPOLL | ET_STAT) }
  171.  
  172. # Temporary signal subtypes, used during signal dispatch semantics
  173. # deprecation and reformation.
  174.  
  175. sub ET_SIGNAL_EXPLICIT   () { 0x0800 }  # Explicitly requested signal.
  176. sub ET_SIGNAL_COMPATIBLE () { 0x1000 }  # Backward-compatible semantics.
  177.  
  178. # A hash of reserved names.  It's used to test whether someone is
  179. # trying to use an internal event directoly.  XXX - These are not fat
  180. # commas, otherwise the symbolic constants would be stringified.
  181.  
  182. my %poes_own_events =
  183.   ( EN_CHILD  , 1, EN_GC     , 1, EN_PARENT , 1, EN_SCPOLL , 1,
  184.     EN_SIGNAL , 1, EN_START  , 1, EN_STOP   , 1, EN_STAT,    1,
  185.   );
  186.  
  187. # These are ways a child may come or go.
  188.  
  189. sub CHILD_GAIN   () { 'gain'   }  # The session was inherited from another.
  190. sub CHILD_LOSE   () { 'lose'   }  # The session is no longer this one's child.
  191. sub CHILD_CREATE () { 'create' }  # The session was created as a child of this.
  192.  
  193. # Argument offsets for different types of internally generated events.
  194. # -><- Exporting (EXPORT_OK) these would let people stop depending on
  195. # positions for them.
  196.  
  197. sub EA_SEL_HANDLE () { 0 }
  198. sub EA_SEL_MODE   () { 1 }
  199.  
  200. # Queues with this many events (or more) are considered to be "large",
  201. # and different strategies are used to find events within them.
  202.  
  203. sub LARGE_QUEUE_SIZE () { 512 }
  204.  
  205. #------------------------------------------------------------------------------
  206. # Debugging and configuration constants.
  207.  
  208. # Shorthand for defining a trace constant.
  209. sub define_trace {
  210.   no strict 'refs';
  211.   foreach my $name (@_) {
  212.     next if defined *{"TRACE_$name"}{CODE};
  213.     my $trace_value = &TRACE_DEFAULT;
  214.     eval "sub TRACE_$name () { $trace_value }";
  215.     die if $@;
  216.   }
  217. }
  218.  
  219. # Shorthand for defining an assert constant.
  220. sub define_assert {
  221.   no strict 'refs';
  222.   foreach my $name (@_) {
  223.     next if defined *{"ASSERT_$name"}{CODE};
  224.     my $assert_value = &ASSERT_DEFAULT;
  225.     eval "sub ASSERT_$name () { $assert_value }";
  226.     die if $@;
  227.   }
  228. }
  229.  
  230. # Debugging flags for subsystems.  They're done as double evals here
  231. # so that someone may define them before using POE::Kernel (or POE),
  232. # and the pre-defined value will take precedence over the defaults
  233. # here.
  234.  
  235. BEGIN {
  236.  
  237.   # Assimilate POE_TRACE_* and POE_ASSERT_* environment variables.
  238.   # Environment variables override everything else.
  239.   while (my ($var, $val) = each %ENV) {
  240.     next unless $var =~ /^POE_((?:TRACE|ASSERT)_[A-Z_]+)$/;
  241.     my $const = $1;
  242.  
  243.     # Copy so we don't hurt our environment.  Make sure strings are
  244.     # wrapped in quotes.
  245.     my $value = $val;
  246.     $value =~ tr['"][]d;
  247.     $value = qq("$value") if $value =~ /\D/;
  248.  
  249.     BEGIN { $^W = 0; }
  250.  
  251.     eval "sub $const () { $value }";
  252.     die if $@;
  253.   }
  254.  
  255.   # TRACE_FILENAME is special.
  256.   {
  257.     no strict 'refs';
  258.     my $trace_filename = TRACE_FILENAME() if defined &TRACE_FILENAME;
  259.     if (defined $trace_filename) {
  260.       open TRACE_FILE, ">$trace_filename"
  261.         or die "can't open trace file `$trace_filename': $!";
  262.       CORE::select((CORE::select(TRACE_FILE), $| = 1)[0]);
  263.     }
  264.     else {
  265.       *TRACE_FILE = *STDERR;
  266.     }
  267.   }
  268.   # TRACE_DEFAULT changes the default value for other TRACE_*
  269.   # constants.  Since define_trace() uses TRACE_DEFAULT internally, it
  270.   # can't be used to define TRACE_DEFAULT itself.
  271.  
  272.   defined &TRACE_DEFAULT or eval "sub TRACE_DEFAULT () { 0 }";
  273.  
  274.   define_trace qw(
  275.     EVENTS FILES PROFILE REFCNT RETVALS SESSIONS SIGNALS STATISTICS
  276.   );
  277.  
  278.   # See the notes for TRACE_DEFAULT, except read ASSERT and assert
  279.   # where you see TRACE and trace.
  280.  
  281.   defined &ASSERT_DEFAULT or eval "sub ASSERT_DEFAULT () { 0 }";
  282.  
  283.   define_assert qw(DATA EVENTS FILES RETVALS USAGE);
  284. }
  285.  
  286. # This is a second BEGIN block so TRACE_STATISTICS may be defined
  287. # already.
  288.  
  289. BEGIN {
  290.   # The Kernel's queue is "idle" if there is one or two events in it.
  291.   # One event is for the signal poller; a second event is for the
  292.   # profiler timer tick, if TRACE_PROFILE is enabled.
  293.  
  294.   my $idle_queue_size = 1;
  295.   $idle_queue_size++ if TRACE_PROFILE;
  296.   eval "sub IDLE_QUEUE_SIZE () { $idle_queue_size }";
  297.   die if $@;
  298. };
  299.  
  300. #------------------------------------------------------------------------------
  301. # Helpers to carp, croak, confess, cluck, warn and die with whatever
  302. # trace file we're using today.  _trap is reserved for internal
  303. # errors.
  304.  
  305. {
  306.   # This block abstracts away a particular piece of voodoo, since we're about
  307.   # to call it many times. This is all a big closure around the following two
  308.   # variables, allowing us to swap out and replace handlers without the need
  309.   # for mucking up the namespace or the kernel itself.
  310.   my ($orig_warn_handler, $orig_die_handler);
  311.  
  312.   # _trap_death replaces the current __WARN__ and __DIE__ handlers with our own.
  313.   # We keep the defaults around so we can put them back when we're done.
  314.   # Specifically this is necessary, it seems, for older perls that don't
  315.   # respect the C< local *STDERR = *TRACE_FILE >.
  316.   sub _trap_death {
  317.     $orig_warn_handler = $SIG{__WARN__};
  318.     $orig_die_handler = $SIG{__DIE__};
  319.  
  320.     $SIG{__WARN__} = sub { print TRACE_FILE $_[0] };
  321.     $SIG{__DIE__} = sub { print TRACE_FILE $_[0]; die $@; };
  322.  
  323.   }
  324.  
  325.   # _release_death puts the original __WARN__ and __DIE__ handlers back in
  326.   # place. Hopefully this is zero-impact camping. The hope is that we can
  327.   # do our trace magic without impacting anyone else.
  328.   sub _release_death {
  329.     $SIG{__WARN__} = $orig_warn_handler;
  330.     $SIG{__DIE__} = $orig_die_handler;
  331.   }
  332. }
  333.  
  334.  
  335. sub _trap {
  336.   local $Carp::CarpLevel = $Carp::CarpLevel + 1;
  337.   local *STDERR = *TRACE_FILE;
  338.  
  339.   _trap_death();
  340.  
  341.   confess(
  342.     "Please mail the following information to bug-POE\@rt.cpan.org:\n@_"
  343.   );
  344.  
  345.   _release_death();
  346. }
  347.  
  348. sub _croak {
  349.   local $Carp::CarpLevel = $Carp::CarpLevel + 1;
  350.   local *STDERR = *TRACE_FILE;
  351.  
  352.   _trap_death();
  353.  
  354.   croak @_;
  355.  
  356.   _release_death();
  357.  
  358. }
  359.  
  360. sub _confess {
  361.   local $Carp::CarpLevel = $Carp::CarpLevel + 1;
  362.   local *STDERR = *TRACE_FILE;
  363.   _trap_death();
  364.   confess @_;
  365.   _release_death();
  366. }
  367.  
  368. sub _cluck {
  369.   local $Carp::CarpLevel = $Carp::CarpLevel + 1;
  370.   local *STDERR = *TRACE_FILE;
  371.  
  372.   _trap_death();
  373.  
  374.   cluck @_;
  375.  
  376.   _release_death();
  377. }
  378.  
  379. sub _carp {
  380.   local $Carp::CarpLevel = $Carp::CarpLevel + 1;
  381.   local *STDERR = *TRACE_FILE;
  382.  
  383.   _trap_death();
  384.  
  385.   carp @_;
  386.  
  387.   _release_death();
  388. }
  389.  
  390. sub _warn {
  391.   my ($package, $file, $line) = caller();
  392.   my $message = join("", @_);
  393.   $message .= " at $file line $line\n" unless $message =~ /\n$/;
  394.  
  395.   _trap_death();
  396.  
  397.   warn $message;
  398.  
  399.   _release_death();
  400. }
  401.  
  402. sub _die {
  403.   my ($package, $file, $line) = caller();
  404.   my $message = join("", @_);
  405.   $message .= " at $file line $line\n" unless $message =~ /\n$/;
  406.   local *STDERR = *TRACE_FILE;
  407.  
  408.   _trap_death();
  409.  
  410.   die $message;
  411.  
  412.   _release_death();
  413. }
  414.  
  415. #------------------------------------------------------------------------------
  416. # Adapt POE::Kernel's personality to whichever event loop is present.
  417.  
  418. BEGIN {
  419.   my $used_first;
  420.   local $SIG{__DIE__} = "DEFAULT";
  421.  
  422.   # First see if someone has loaded a POE::Loop or XS version
  423.   # explicitly.  Make a note of it if they already have.  The next
  424.   # loop through %INC will just verify that two loops aren't active at
  425.   # once.
  426.   foreach my $file (keys %INC) {
  427.     if ($file =~ /^POE\/(?:XS\/)?Loop\/(.+)\.pm$/) {
  428.       $used_first = $1;
  429.     }
  430.   }
  431.  
  432.   foreach my $file (keys %INC) {
  433.     # Remove IO/ so we can load POE::Loop::Poll instead of
  434.     # POE::Loop::IO/Poll.
  435.     #
  436.     # TODO - A better convention would be to replace the path
  437.     # separators with hyphens and rename Loop/Poll.pm to
  438.     # Loop/IO-Poll.pm.  Foresight > Hindsight.
  439.     my $pared_file = $file;
  440.     $pared_file =~ s/^IO\///;
  441.     next if $pared_file =~ /\//;
  442.  
  443.     my $module = $pared_file;
  444.     substr($module, -3) = "";
  445.  
  446.     # Modules can die with "not really dying" if they've loaded
  447.     # something else.  This exception prevents the rest of the
  448.     # originally used module from being parsed, so the module it's
  449.     # handed off to takes over.
  450.  
  451.     # Try for the XS version first.  If it fails, try the plain
  452.     # version.  If that fails, we're up a creek.
  453.     my $mod = "POE::XS::Loop::$module";
  454.     eval "require $mod";
  455.     if ($@ =~ /^Can't locate/) {
  456.       $mod = "POE::Loop::$module";
  457.       eval "require $mod";
  458.     }
  459.  
  460.     next if $@ =~ /^Can't locate/;
  461.     die if $@ and $@ !~ /not really dying/;
  462.  
  463.     if (defined $used_first and $used_first ne $module) {
  464.       die(
  465.         "*\n",
  466.         "* POE can't use multiple event loops at once.\n",
  467.         "* You used $used_first and $module.\n",
  468.         "*\n",
  469.       );
  470.     }
  471.  
  472.     $used_first = $module;
  473.   }
  474.  
  475.   unless (defined $used_first) {
  476.     $used_first = "POE::XS::Loop::Select";
  477.     eval "require $used_first";
  478.     if ($@ and $@ =~ /^Can't locate/) {
  479.       $used_first =~ s/XS:://;
  480.       eval "require $used_first";
  481.     }
  482.     if ($@) {
  483.       die(
  484.         "*\n",
  485.         "* POE can't use $used_first:\n",
  486.         "* $@\n",
  487.         "*\n",
  488.       );
  489.     }
  490.   }
  491. }
  492.  
  493. #------------------------------------------------------------------------------
  494. # Include resource modules here.  Later, when we have the option of XS
  495. # versions, we'll adapt this to include them if they're available.
  496.  
  497. use POE::Resources;
  498.  
  499. ###############################################################################
  500. # Helpers.
  501.  
  502. ### Resolve $whatever into a session reference, trying every method we
  503. ### can until something succeeds.
  504.  
  505. sub _resolve_session {
  506.   my ($self, $whatever) = @_;
  507.   my $session;
  508.  
  509.   # Resolve against sessions.
  510.   $session = $self->_data_ses_resolve($whatever);
  511.   return $session if defined $session;
  512.  
  513.   # Resolve against IDs.
  514.   $session = $self->_data_sid_resolve($whatever);
  515.   return $session if defined $session;
  516.  
  517.   # Resolve against aliases.
  518.   $session = $self->_data_alias_resolve($whatever);
  519.   return $session if defined $session;
  520.  
  521.   # Resolve against the Kernel itself.  Use "eq" instead of "==" here
  522.   # because $whatever is often a string.
  523.   return $whatever if $whatever eq $self;
  524.  
  525.   # We don't know what it is.
  526.   return undef;
  527. }
  528.  
  529. ### Test whether POE has become idle.
  530.  
  531. sub _test_if_kernel_is_idle {
  532.   my $self = shift;
  533.  
  534.   if (TRACE_REFCNT) {
  535.     _warn(
  536.       "<rc> ,----- Kernel Activity -----\n",
  537.       "<rc> | Events : ", $kr_queue->get_item_count(), "\n",
  538.       "<rc> | Files  : ", $self->_data_handle_count(), "\n",
  539.       "<rc> | Extra  : ", $self->_data_extref_count(), "\n",
  540.       "<rc> | Procs  : $kr_child_procs\n",
  541.       "<rc> `---------------------------\n",
  542.       "<rc> ..."
  543.      );
  544.   }
  545.  
  546.   unless ( $kr_queue->get_item_count() > IDLE_QUEUE_SIZE or
  547.            $self->_data_handle_count() or
  548.            $self->_data_extref_count() or
  549.            $kr_child_procs
  550.          ) {
  551.  
  552.     $self->_data_ev_enqueue
  553.       ( $self, $self, EN_SIGNAL, ET_SIGNAL, [ 'IDLE' ],
  554.         __FILE__, __LINE__, time(),
  555.       ) if $self->_data_ses_count();
  556.   }
  557. }
  558.  
  559. ### Explain why a session could not be resolved.
  560.  
  561. sub _explain_resolve_failure {
  562.   my ($self, $whatever) = @_;
  563.   local $Carp::CarpLevel = 2;
  564.  
  565.   if (ASSERT_DATA) {
  566.     _trap "<dt> Cannot resolve ``$whatever'' into a session reference";
  567.   }
  568.  
  569.   $! = ESRCH;
  570.   TRACE_RETVALS  and _carp    "<rv> session not resolved: $!";
  571.   ASSERT_RETVALS and _confess "<rv> session not resolved: $!";
  572. }
  573.  
  574. ### Explain why a function is returning unsuccessfully.
  575.  
  576. sub _explain_return {
  577.   my ($self, $message) = @_;
  578.   local $Carp::CarpLevel = 2;
  579.  
  580.   ASSERT_RETVALS and _confess "<rv> $message";
  581.   TRACE_RETVALS  and _carp    "<rv> $message";
  582. }
  583.  
  584. ### Explain how the user made a mistake calling a function.
  585.  
  586. sub _explain_usage {
  587.   my ($self, $message) = @_;
  588.   local $Carp::CarpLevel = 2;
  589.  
  590.   ASSERT_USAGE   and _confess "<us> $message";
  591.   ASSERT_RETVALS and _confess "<rv> $message";
  592.   TRACE_RETVALS  and _carp    "<rv> $message";
  593. }
  594.  
  595. #==============================================================================
  596. # SIGNALS
  597. #==============================================================================
  598.  
  599. #------------------------------------------------------------------------------
  600. # Register or remove signals.
  601.  
  602. # Public interface for adding or removing signal handlers.
  603.  
  604. sub sig {
  605.   my ($self, $signal, $event_name) = @_;
  606.  
  607.   if (ASSERT_USAGE) {
  608.     _confess "<us> undefined signal in sig()" unless defined $signal;
  609.     _carp(
  610.       "<us> The '$event_name' event is one of POE's own.  Its " .
  611.       "effect cannot be achieved assigning it to a signal"
  612.     ) if defined($event_name) and exists($poes_own_events{$event_name});
  613.   };
  614.  
  615.   if (defined $event_name) {
  616.     $self->_data_sig_add($kr_active_session, $signal, $event_name);
  617.   }
  618.   else {
  619.     $self->_data_sig_remove($kr_active_session, $signal);
  620.   }
  621. }
  622.  
  623. # Public interface for posting signal events.
  624.  
  625. sub signal {
  626.   my ($self, $destination, $signal, @etc) = @_;
  627.  
  628.   if (ASSERT_USAGE) {
  629.     _confess "<us> undefined destination in signal()"
  630.       unless defined $destination;
  631.     _confess "<us> undefined signal in signal()" unless defined $signal;
  632.   };
  633.  
  634.   my $session = $self->_resolve_session($destination);
  635.   unless (defined $session) {
  636.     $self->_explain_resolve_failure($destination);
  637.     return;
  638.   }
  639.  
  640.   $self->_data_ev_enqueue
  641.     ( $session, $kr_active_session,
  642.       EN_SIGNAL, ET_SIGNAL, [ $signal, @etc ],
  643.       (caller)[1,2], time(),
  644.     );
  645. }
  646.  
  647. # Public interface for flagging signals as handled.  This will replace
  648. # the handlers' return values as an implicit flag.  Returns undef so
  649. # it may be used as the last function in an event handler.
  650.  
  651. sub sig_handled {
  652.   my $self = shift;
  653.   $self->_data_sig_handled();
  654.  
  655.   if ($kr_active_event eq EN_SIGNAL) {
  656.     _die(
  657.       ",----- DEPRECATION ERROR -----\n",
  658.       "| Session ", $self->_data_alias_loggable($kr_active_session), ":\n",
  659.       "| handled a _signal event.  You must register a handler with sig().\n",
  660.       "`-----------------------------\n",
  661.     );
  662.   }
  663. }
  664.  
  665. # Attach a window or widget's destroy/closure to the UIDESTROY signal.
  666.  
  667. sub signal_ui_destroy {
  668.   my ($self, $window) = @_;
  669.   $self->loop_attach_uidestroy($window);
  670. }
  671.  
  672.  
  673. #==============================================================================
  674. # KERNEL
  675. #==============================================================================
  676.  
  677. sub new {
  678.   my $type = shift;
  679.  
  680.   # Prevent multiple instances, no matter how many times it's called.
  681.   # This is a backward-compatibility enhancement for programs that
  682.   # have used versions prior to 0.06.  It also provides a convenient
  683.   # single entry point into the entirety of POE's state: point a
  684.   # Dumper module at it, and you'll see a hideous tree of knowledge.
  685.   # Be careful, though.  Its apples bite back.
  686.   unless (defined $poe_kernel) {
  687.  
  688.     # Create our master queue.
  689.     $kr_queue = POE::Queue::Array->new();
  690.  
  691.     my $self = $poe_kernel = bless
  692.       [ undef,               # KR_SESSIONS - loaded from POE::Resource::Sessions
  693.         undef,               # KR_FILENOS - loaded from POE::Resource::FileHandles
  694.         undef,               # KR_SIGNALS - loaded from POE::Resource::Signals
  695.         undef,               # KR_ALIASES - loaded from POE::Resource::Aliases
  696.         \$kr_active_session, # KR_ACTIVE_SESSION - should this be handled by POE::Resource::Sessions?
  697.         $kr_queue,           # KR_QUEUE - should this be extracted into a Resource ?
  698.         undef,               # KR_ID
  699.         undef,               # KR_SESSION_IDS - loaded from POE::Resource::SIDS
  700.         undef,               # KR_SID_SEQ - loaded from POE::Resource::SIDS - is a scalar ref
  701.         undef,               # KR_EXTRA_REFS
  702.         undef,               # KR_SIZE
  703.         \$kr_run_warning,    # KR_RUN
  704.         \$kr_active_event,   # KR_ACTIVE_EVENT
  705.       ], $type;
  706.  
  707.     POE::Resources->initialize();
  708.  
  709.     # Kernel ID, based on Philip Gwyn's code.  I hope he still can
  710.     # recognize it.  KR_SESSION_IDS is a hash because it will almost
  711.     # always be sparse.  This goes before signals are registered
  712.     # because it sometimes spawns /bin/hostname or the equivalent,
  713.     # generating spurious CHLD signals before the Kernel is fully
  714.     # initialized.
  715.  
  716.     my $hostname = eval { (POSIX::uname)[1] };
  717.     $hostname = hostname() unless defined $hostname;
  718.  
  719.     $self->[KR_ID] = $hostname . '-' .  unpack('H*', pack('N*', time, $$));
  720.     $self->_data_sid_set($self->[KR_ID], $self);
  721.  
  722.     # Initialize subsystems.  The order is important.
  723.  
  724.     # We need events before sessions, and the kernel's session before
  725.     # it can start polling for signals.  Statistics gathering requires
  726.     # a polling event as well, so it goes late.
  727.     $self->_data_ev_initialize($kr_queue);
  728.     $self->_initialize_kernel_session();
  729.     $self->_data_stat_initialize() if TRACE_STATISTICS;
  730.     $self->_data_sig_initialize();
  731.     $self->_data_magic_initialize();
  732.  
  733.     # These other subsystems don't have strange interactions.
  734.     $self->_data_handle_initialize($kr_queue);
  735.   }
  736.  
  737.   # Return the global instance.
  738.   $poe_kernel;
  739. }
  740.  
  741. #------------------------------------------------------------------------------
  742. # Send an event to a session right now.  Used by _disp_select to
  743. # expedite select() events, and used by run() to deliver posted events
  744. # from the queue.
  745.  
  746. # Dispatch an event to its session.  A lot of work goes on here.
  747.  
  748. sub _dispatch_event {
  749.   my ( $self,
  750.        $session, $source_session, $event, $type, $etc, $file, $line,
  751.        $time, $seq
  752.      ) = @_;
  753.  
  754.   if (ASSERT_EVENTS) {
  755.     _confess "<ev> undefined dest session" unless defined $session;
  756.     _confess "<ev> undefined source session" unless defined $source_session;
  757.   };
  758.  
  759.   if (TRACE_EVENTS) {
  760.     my $log_session = $session;
  761.     $log_session =  $self->_data_alias_loggable($session)
  762.       unless $type & ET_START;
  763.     my $string_etc = join(" ", map { defined() ? $_ : "(undef)" } @$etc);
  764.     _warn(
  765.       "<ev> Dispatching event $seq ``$event'' ($string_etc) from ",
  766.       $self->_data_alias_loggable($source_session), " to $log_session"
  767.     );
  768.   }
  769.  
  770.   my $local_event = $event;
  771.  
  772.   $self->_stat_profile($event) if TRACE_PROFILE;
  773.  
  774.   # Pre-dispatch processing.
  775.  
  776.   unless ($type & (ET_POST | ET_CALL)) {
  777.  
  778.     # A "select" event has just come out of the queue.  Reset its
  779.     # actual state to its requested state before handling the event.
  780.  
  781.     if ($type & ET_SELECT) {
  782.       $self->_data_handle_resume_requested_state(@$etc);
  783.     }
  784.  
  785.     # Some sessions don't do anything in _start and expect their
  786.     # creators to provide a start-up event.  This means we can't
  787.     # &_collect_garbage at _start time.  Instead, we post a
  788.     # garbage-collect event at start time, and &_collect_garbage at
  789.     # delivery time.  This gives the session's creator time to do
  790.     # things with it before we reap it.
  791.  
  792.     elsif ($type & ET_GC) {
  793.       $self->_data_ses_collect_garbage($session);
  794.       return 0;
  795.     }
  796.  
  797.     # Preprocess signals.  This is where _signal is translated into
  798.     # its registered handler's event name, if there is one.
  799.  
  800.     elsif ($type & ET_SIGNAL) {
  801.       my $signal = $etc->[0];
  802.  
  803.       if (TRACE_SIGNALS) {
  804.         _warn(
  805.           "<sg> dispatching ET_SIGNAL ($signal) to ",
  806.           $self->_data_alias_loggable($session)
  807.         );
  808.       }
  809.  
  810.       # Step 0: Reset per-signal structures.
  811.  
  812.       $self->_data_sig_reset_handled($signal);
  813.  
  814.       # Step 1: Propagate the signal to sessions that are watching it.
  815.  
  816.       if ($self->_data_sig_explicitly_watched($signal)) {
  817.         my %signal_watchers = $self->_data_sig_watchers($signal);
  818.         while (my ($session, $event) = each %signal_watchers) {
  819.           my $session_ref = $self->_data_ses_resolve($session);
  820.  
  821.           if (TRACE_SIGNALS) {
  822.             _warn(
  823.               "<sg> propagating explicit signal $event ($signal) ",
  824.               "to ", $self->_data_alias_loggable($session_ref)
  825.             );
  826.           }
  827.  
  828.           $self->_dispatch_event
  829.             ( $session_ref, $self,
  830.               $event, ET_SIGNAL_EXPLICIT, $etc,
  831.               $file, $line, time(), -__LINE__
  832.             );
  833.         }
  834.       }
  835.     }
  836.  
  837.     # Save the name of the event we're processing.
  838.     my $hold_active_event = $kr_active_event;
  839.     $kr_active_event = $event;
  840.  
  841.     # Step 2: Propagate the signal to this session's children.  This
  842.     # happens first, making the signal's traversal through the
  843.     # parent/child tree depth first.  It ensures that signals posted
  844.     # to the Kernel are delivered to the Kernel last.
  845.  
  846.     if ($type & (ET_SIGNAL | ET_SIGNAL_COMPATIBLE)) {
  847.       my $signal = $etc->[0];
  848.       foreach ($self->_data_ses_get_children($session)) {
  849.  
  850.         if (TRACE_SIGNALS) {
  851.           _warn(
  852.             "<sg> propagating compatible signal ($signal) to ",
  853.             $self->_data_alias_loggable($_)
  854.           );
  855.         }
  856.  
  857.         $self->_dispatch_event
  858.           ( $_, $self,
  859.             $event, ET_SIGNAL_COMPATIBLE, $etc,
  860.             $file, $line, time(), -__LINE__
  861.           );
  862.  
  863.         if (TRACE_SIGNALS) {
  864.           _warn(
  865.             "<sg> propagated to ",
  866.             $self->_data_alias_loggable($_)
  867.           );
  868.         }
  869.       }
  870.  
  871.       # If this session already received a signal in step 1, then
  872.       # ignore dispatching it again in this step.
  873.       return if (
  874.         ($type & ET_SIGNAL_COMPATIBLE) and
  875.         $self->_data_sig_is_watched_by_session($signal, $session)
  876.       );
  877.     }
  878.   }
  879.  
  880.   # The destination session doesn't exist.  This indicates sloppy
  881.   # programming, possibly within POE::Kernel.
  882.  
  883.   unless ($self->_data_ses_exists($session)) {
  884.     if (TRACE_EVENTS) {
  885.       _warn(
  886.         "<ev> discarding event $seq ``$event'' to nonexistent ",
  887.         $self->_data_alias_loggable($session)
  888.       );
  889.     }
  890.     return;
  891.   }
  892.  
  893.   if (TRACE_EVENTS) {
  894.     _warn(
  895.     "<ev> dispatching event $seq ``$event'' to ",
  896.       $self->_data_alias_loggable($session)
  897.     );
  898.     if ($event eq EN_SIGNAL) {
  899.       _warn("<ev>     signal($etc->[0])");
  900.     }
  901.   }
  902.  
  903.   # Prepare to call the appropriate handler.  Push the current active
  904.   # session on Perl's call stack.
  905.   my $hold_active_session = $kr_active_session;
  906.   $kr_active_session = $session;
  907.  
  908.   my $hold_active_event = $kr_active_event;
  909.   $kr_active_event = $event;
  910.  
  911.   # Clear the implicit/explicit signal handler flags for this event
  912.   # dispatch.  We'll use them afterward to carp at the user if they
  913.   # handled something implicitly but not explicitly.
  914.  
  915.   $self->_data_sig_clear_handled_flags();
  916.  
  917.   # Dispatch the event, at long last.
  918.   my $before;
  919.   if (TRACE_STATISTICS) {
  920.       $before = time();
  921.   }
  922.   my $return;
  923.   if (wantarray) {
  924.     $return =
  925.       [ $session->_invoke_state($source_session, $event, $etc, $file, $line) ];
  926.   }
  927.   else {
  928.     $return =
  929.       $session->_invoke_state($source_session, $event, $etc, $file, $line);
  930.   }
  931.  
  932.   if (TRACE_STATISTICS) {
  933.       my $after = time();
  934.       my $elapsed = $after - $before;
  935.       if ($type & ET_MASK_USER) {
  936.       $self->_data_stat_add('user_seconds', $elapsed);
  937.       $self->_data_stat_add('user_events', 1);
  938.       }
  939.   }
  940.  
  941.   # Stringify the handler's return value if it belongs in the POE
  942.   # namespace.  $return's scope exists beyond the post-dispatch
  943.   # processing, which includes POE's garbage collection.  The scope
  944.   # bleed was known to break determinism in surprising ways.
  945.  
  946.   if (defined $return and substr(ref($return), 0, 5) eq 'POE::') {
  947.     $return = "$return";
  948.   }
  949.  
  950.   # Pop the active session, now that it's not active anymore.
  951.   $kr_active_session = $hold_active_session;
  952.  
  953.   if (TRACE_EVENTS) {
  954.     my $string_ret = $return;
  955.     $string_ret = "undef" unless defined $string_ret;
  956.     _warn("<ev> event $seq ``$event'' returns ($string_ret)\n");
  957.   }
  958.  
  959.   # Post-dispatch processing.
  960.   #
  961.   # If this invocation is a user event, see if the destination session
  962.   # needs to be garbage collected.  Also check the source session if
  963.   # it's different from the destination.
  964.   #
  965.   # If the invocation is a call, and the destination session is
  966.   # different from the calling one, test it for garbage collection.
  967.   # We avoid testing if the source and destination are the same
  968.   # because at some point we'll hit a user event that will catch it.
  969.   #
  970.   # -><- We test whether the sessions exist.  They should, but we've
  971.   # been getting double-free errors lately.  I think we should avoid
  972.   # the double free some other way, but this is the most expedient
  973.   # method.
  974.   #
  975.   # -><- It turns out that POE::NFA->stop() may have discarded
  976.   # sessions already, so we need to do the GC test anyway.  Maybe some
  977.   # sort of mark-and-sweep can avoid redundant tests.
  978.  
  979.   if ($type & ET_POST) {
  980.     $self->_data_ses_collect_garbage($session)
  981.       if $self->_data_ses_exists($session);
  982.     $self->_data_ses_collect_garbage($source_session)
  983.       if ( $session != $source_session and
  984.            $self->_data_ses_exists($source_session)
  985.          );
  986.   }
  987.   elsif ($type & ET_CALL and $source_session != $session) {
  988.     $self->_data_ses_collect_garbage($session)
  989.       if $self->_data_ses_exists($session);
  990.   }
  991.  
  992.   # Step 3: Check for death by terminal signal.
  993.  
  994.   if ($type & (ET_SIGNAL | ET_SIGNAL_EXPLICIT | ET_SIGNAL_COMPATIBLE)) {
  995.     $self->_data_sig_touched_session($session, $event, $return, $etc->[0]);
  996.  
  997.     if ($type & ET_SIGNAL) {
  998.       $self->_data_sig_free_terminated_sessions();
  999.     }
  1000.   }
  1001.  
  1002.   # These types of events require garbage collection afterwards, but
  1003.   # they don't need any other processing.
  1004.  
  1005.   elsif ($type & (ET_ALARM | ET_SELECT)) {
  1006.     $self->_data_ses_collect_garbage($session);
  1007.   }
  1008.  
  1009.   # Recover the event being processed.
  1010.   $kr_active_event = $hold_active_event;
  1011.  
  1012.   # Return what the handler did.  This is used for call().
  1013.   return @$return if wantarray;
  1014.   return $return;
  1015. }
  1016.  
  1017. #------------------------------------------------------------------------------
  1018. # POE's main loop!  Now with Tk and Event support!
  1019.  
  1020. # Do pre-run startup.  Initialize the event loop, and allocate a
  1021. # session structure to represent the Kernel.
  1022.  
  1023. sub _initialize_kernel_session {
  1024.   my $self = shift;
  1025.  
  1026.   $self->loop_initialize();
  1027.  
  1028.   $kr_active_session = $self;
  1029.   $self->_data_ses_allocate($self, $self->[KR_ID], undef);
  1030. }
  1031.  
  1032. # Do post-run cleanup.
  1033.  
  1034. sub finalize_kernel {
  1035.   my $self = shift;
  1036.  
  1037.   # Disable signal watching since there's now no place for them to go.
  1038.   foreach ($self->_data_sig_get_safe_signals()) {
  1039.     $self->loop_ignore_signal($_);
  1040.   }
  1041.  
  1042.   # The main loop is done, no matter which event library ran it.
  1043.   $self->loop_finalize();
  1044.   $self->_data_extref_finalize();
  1045.   $self->_data_sid_finalize();
  1046.   $self->_data_sig_finalize();
  1047.   $self->_data_alias_finalize();
  1048.   $self->_data_handle_finalize();
  1049.   $self->_data_ev_finalize();
  1050.   $self->_data_ses_finalize();
  1051.   $self->_data_stat_finalize() if TRACE_PROFILE or TRACE_STATISTICS;
  1052.   $self->_data_magic_finalize();
  1053. }
  1054.  
  1055. sub run_one_timeslice {
  1056.   my $self = shift;
  1057.   return undef unless $self->_data_ses_count();
  1058.   $self->loop_do_timeslice();
  1059.   unless ($self->_data_ses_count()) {
  1060.     $self->finalize_kernel();
  1061.     $kr_run_warning |= KR_RUN_DONE;
  1062.   }
  1063. }
  1064.  
  1065. sub run {
  1066.   # So run() can be called as a class method.
  1067.   my $self = $poe_kernel;
  1068.  
  1069.   # Flag that run() was called.
  1070.   $kr_run_warning |= KR_RUN_CALLED;
  1071.  
  1072.   $self->loop_run();
  1073.  
  1074.   # Clean up afterwards.
  1075.   $self->finalize_kernel();
  1076.   $kr_run_warning |= KR_RUN_DONE;
  1077. }
  1078.  
  1079. # Stops the kernel cold.  XXX Experimental!
  1080. # No events happen as a result of this, all structures are cleaned up
  1081. # except the current session which will be cleaned up when the current
  1082. # state handler returns.
  1083. sub stop {
  1084.   # So stop() can be called as a class method.
  1085.   my $self = $poe_kernel;
  1086.  
  1087.   my @children = ($self);
  1088.   foreach my $session (@children) {
  1089.     push @children, $self->_data_ses_get_children($session);
  1090.   }
  1091.  
  1092.   # Remove the kernel itself.
  1093.   shift @children;
  1094.  
  1095.   # Walk backwards to avoid inconsistency errors.
  1096.   foreach my $session (reverse @children) {
  1097.     $self->_data_ses_free($session);
  1098.   }
  1099.  
  1100.   # So new sessions will not be child of the current defunct session.
  1101.   $kr_active_session = $self;
  1102.  
  1103.   undef;
  1104. }
  1105.  
  1106. #------------------------------------------------------------------------------
  1107.  
  1108. sub DESTROY {
  1109.   my $self = shift;
  1110.  
  1111.   # Warn that a session never had the opportunity to run if one was
  1112.   # created but run() was never called.
  1113.  
  1114.   unless ($kr_run_warning & KR_RUN_CALLED) {
  1115.     _warn("POE::Kernel's run() method was never called.\n")
  1116.       if $kr_run_warning & KR_RUN_SESSION;
  1117.   }
  1118. }
  1119.  
  1120. #------------------------------------------------------------------------------
  1121. # _invoke_state is what _dispatch_event calls to dispatch a transition
  1122. # event.  This is the kernel's _invoke_state so it can receive events.
  1123. # These are mostly signals, which are propagated down in
  1124. # _dispatch_event.
  1125.  
  1126. sub _invoke_state {
  1127.   my ($self, $source_session, $event, $etc) = @_;
  1128.  
  1129.   # This is an event loop to poll for child processes without needing
  1130.   # to catch SIGCHLD.
  1131.  
  1132.   if ($event eq EN_SCPOLL) {
  1133.  
  1134.     if (TRACE_SIGNALS) {
  1135.       _warn("<sg> POE::Kernel is polling for signals at " . time())
  1136.     }
  1137.  
  1138.     # Reap children for as long as waitpid(2) says something
  1139.     # interesting has happened.  -><- This has a strong possibility of
  1140.     # an infinite loop.
  1141.  
  1142.     my $pid;
  1143.     while ($pid = waitpid(-1, WNOHANG)) {
  1144.  
  1145.       # waitpid(2) returned a process ID.  Emit an appropriate SIGCHLD
  1146.       # event and loop around again.
  1147.  
  1148.       if ((RUNNING_IN_HELL and $pid < -1) or ($pid > 0)) {
  1149.         if (RUNNING_IN_HELL or WIFEXITED($?) or WIFSIGNALED($?)) {
  1150.  
  1151.           if (TRACE_SIGNALS) {
  1152.             _warn("<sg> POE::Kernel detected SIGCHLD (pid=$pid; exit=$?)");
  1153.           }
  1154.  
  1155.           $self->_data_ev_enqueue
  1156.             ( $self, $self, EN_SIGNAL, ET_SIGNAL, [ 'CHLD', $pid, $? ],
  1157.               __FILE__, __LINE__, time(),
  1158.             );
  1159.         }
  1160.         elsif (TRACE_SIGNALS) {
  1161.           _warn("<sg> POE::Kernel detected strange exit (pid=$pid; exit=$?");
  1162.         }
  1163.  
  1164.         if (TRACE_SIGNALS) {
  1165.           _warn("<sg> POE::Kernel will poll again immediately");
  1166.         }
  1167.  
  1168.         next;
  1169.       }
  1170.  
  1171.       # The only other negative value waitpid(2) should return is -1.
  1172.  
  1173.       _trap "internal consistency error: waitpid returned $pid"
  1174.         if $pid != -1;
  1175.  
  1176.       # If the error is an interrupted syscall, poll again right away.
  1177.  
  1178.       if ($! == EINTR) {
  1179.         if (TRACE_SIGNALS) {
  1180.           _warn(
  1181.             "<sg> POE::Kernel's waitpid(2) was interrupted.\n",
  1182.             "POE::Kernel will poll again immediately.\n"
  1183.           );
  1184.         }
  1185.         next;
  1186.       }
  1187.  
  1188.       # No child processes exist.  -><- This is different than
  1189.       # children being present but running.  Maybe this condition
  1190.       # could halt polling entirely, and some UNIVERSAL::fork wrapper
  1191.       # could restart polling when processes are forked.
  1192.  
  1193.       if ($! == ECHILD) {
  1194.         if (TRACE_SIGNALS) {
  1195.           _warn("<sg> POE::Kernel has no child processes");
  1196.         }
  1197.         last;
  1198.       }
  1199.  
  1200.       # Some other error occurred.
  1201.  
  1202.       if (TRACE_SIGNALS) {
  1203.         _warn("<sg> POE::Kernel's waitpid(2) got error: $!");
  1204.       }
  1205.       last;
  1206.     }
  1207.  
  1208.     # If waitpid() returned 0, then we have child processes.
  1209.  
  1210.     $kr_child_procs = !$pid;
  1211.  
  1212.     # The poll loop is over.  Resume slowly polling for signals.
  1213.  
  1214.     if (TRACE_SIGNALS) {
  1215.       _warn("<sg> POE::Kernel will poll again after a delay");
  1216.     }
  1217.  
  1218.     $self->_data_ev_enqueue(
  1219.       $self, $self, EN_SCPOLL, ET_SCPOLL, [ ],
  1220.       __FILE__, __LINE__, time() + 1
  1221.     ) if $self->_data_ses_count() > 1;
  1222.   }
  1223.  
  1224.   # A signal was posted.  Because signals propagate depth-first, this
  1225.   # _invoke_state is called last in the dispatch.  If the signal was
  1226.   # SIGIDLE, then post a SIGZOMBIE if the main queue is still idle.
  1227.  
  1228.   elsif ($event eq EN_SIGNAL) {
  1229.     if ($etc->[0] eq 'IDLE') {
  1230.       unless (
  1231.         $kr_queue->get_item_count() > IDLE_QUEUE_SIZE or
  1232.         $self->_data_handle_count()
  1233.       ) {
  1234.         $self->_data_ev_enqueue
  1235.           ( $self, $self, EN_SIGNAL, ET_SIGNAL, [ 'ZOMBIE' ],
  1236.             __FILE__, __LINE__, time(),
  1237.           );
  1238.       }
  1239.     }
  1240.   }
  1241.  
  1242.   elsif ($event eq EN_STAT) {
  1243.       $self->_data_stat_tick();
  1244.   }
  1245.  
  1246.   return 0;
  1247. }
  1248.  
  1249. #==============================================================================
  1250. # SESSIONS
  1251. #==============================================================================
  1252.  
  1253. # Dispatch _start to a session, allocating it in the kernel's data
  1254. # structures as a side effect.
  1255.  
  1256. sub session_alloc {
  1257.   my ($self, $session, @args) = @_;
  1258.  
  1259.   # If we already returned, then we must reinitialize.  This is so
  1260.   # $poe_kernel->run() will work correctly more than once.
  1261.   if ($kr_run_warning & KR_RUN_DONE) {
  1262.     $kr_run_warning &= ~KR_RUN_DONE;
  1263.     $self->_initialize_kernel_session();
  1264.     $self->_data_stat_initialize() if TRACE_STATISTICS;
  1265.     $self->_data_sig_initialize();
  1266.   }
  1267.  
  1268.   if (ASSERT_DATA) {
  1269.     if ($self->_data_ses_exists($session)) {
  1270.       _trap(
  1271.         "<ss> ", $self->_data_alias_loggable($session), " already exists\a"
  1272.       );
  1273.     }
  1274.   }
  1275.  
  1276.   # Register that a session was created.
  1277.   $kr_run_warning |= KR_RUN_SESSION;
  1278.  
  1279.   # Allocate the session's data structure.  This must be done before
  1280.   # we dispatch anything regarding the new session.
  1281.   my $new_sid = $self->_data_sid_allocate();
  1282.   $self->_data_ses_allocate($session, $new_sid, $kr_active_session);
  1283.  
  1284.   # Tell the new session that it has been created.  Catch the _start
  1285.   # state's return value so we can pass it to the parent with the
  1286.   # _child create.
  1287.   my $return = $self->_dispatch_event(
  1288.     $session, $kr_active_session,
  1289.     EN_START, ET_START, \@args,
  1290.     __FILE__, __LINE__, time(), -__LINE__
  1291.   );
  1292.  
  1293.   # If the child has not detached itself---that is, if its parent is
  1294.   # the currently active session---then notify the parent with a
  1295.   # _child create event.  Otherwise skip it, since we'd otherwise
  1296.   # throw a create without a lose.
  1297.   $self->_dispatch_event(
  1298.     $self->_data_ses_get_parent($session), $self,
  1299.     EN_CHILD, ET_CHILD, [ CHILD_CREATE, $session, $return ],
  1300.     __FILE__, __LINE__, time(), -__LINE__
  1301.   );
  1302.  
  1303.   # Enqueue a delayed garbage-collection event so the session has time
  1304.   # to do its thing before it goes.
  1305.   $self->_data_ev_enqueue(
  1306.     $session, $session, EN_GC, ET_GC, [],
  1307.     __FILE__, __LINE__, time(),
  1308.   );
  1309. }
  1310.  
  1311. # Detach a session from its parent.  This breaks the parent/child
  1312. # relationship between the current session and its parent.  Basically,
  1313. # the current session is given to the Kernel session.  Unlike with
  1314. # _stop, the current session's children follow their parent.
  1315. #
  1316. # TODO - Calling detach_myself() from _start means the parent receives
  1317. # a "_child lose" event without ever seeing "_child create".
  1318.  
  1319. sub detach_myself {
  1320.   my $self = shift;
  1321.  
  1322.   # Can't detach from the kernel.
  1323.   if ($self->_data_ses_get_parent($kr_active_session) == $self) {
  1324.     $! = EPERM;
  1325.     return;
  1326.   }
  1327.  
  1328.   my $old_parent = $self->_data_ses_get_parent($kr_active_session);
  1329.  
  1330.   # Tell the old parent session that the child is departing.
  1331.   $self->_dispatch_event(
  1332.     $old_parent, $self,
  1333.     EN_CHILD, ET_CHILD, [ CHILD_LOSE, $kr_active_session ],
  1334.     (caller)[1,2], time(), -__LINE__
  1335.   );
  1336.  
  1337.   # Tell the new parent (kernel) that it's gaining a child.
  1338.   # (Actually it doesn't care, so we don't do that here, but this is
  1339.   # where the code would go if it ever does in the future.)
  1340.  
  1341.   # Tell the current session that its parentage is changing.
  1342.   $self->_dispatch_event(
  1343.     $kr_active_session, $self,
  1344.     EN_PARENT, ET_PARENT, [ $old_parent, $self ],
  1345.     (caller)[1,2], time(), -__LINE__
  1346.   );
  1347.  
  1348.   $self->_data_ses_move_child($kr_active_session, $self);
  1349.  
  1350.   # Test the old parent for garbage.
  1351.   $self->_data_ses_collect_garbage($old_parent);
  1352.  
  1353.   # Success!
  1354.   return 1;
  1355. }
  1356.  
  1357. # Detach a child from this, the parent.  The session being detached
  1358. # must be a child of the current session.
  1359.  
  1360. sub detach_child {
  1361.   my ($self, $child) = @_;
  1362.  
  1363.   my $child_session = $self->_resolve_session($child);
  1364.   unless (defined $child_session) {
  1365.     $self->_explain_resolve_failure($child);
  1366.     return;
  1367.   }
  1368.  
  1369.   # Can't detach if it belongs to the kernel.  -><- We shouldn't need
  1370.   # to check for this.
  1371.   if ($kr_active_session == $self) {
  1372.     $! = EPERM;
  1373.     return;
  1374.   }
  1375.  
  1376.   # Can't detach if it's not a child of the current session.
  1377.   unless ($self->_data_ses_is_child($kr_active_session, $child_session)) {
  1378.     $! = EPERM;
  1379.     return;
  1380.   }
  1381.  
  1382.   # Tell the current session that the child is departing.
  1383.   $self->_dispatch_event(
  1384.     $kr_active_session, $self,
  1385.     EN_CHILD, ET_CHILD, [ CHILD_LOSE, $child_session ],
  1386.     (caller)[1,2], time(), -__LINE__
  1387.   );
  1388.  
  1389.   # Tell the new parent (kernel) that it's gaining a child.
  1390.   # (Actually it doesn't care, so we don't do that here, but this is
  1391.   # where the code would go if it ever does in the future.)
  1392.  
  1393.   # Tell the child session that its parentage is changing.
  1394.   $self->_dispatch_event(
  1395.     $child_session, $self,
  1396.     EN_PARENT, ET_PARENT, [ $kr_active_session, $self ],
  1397.     (caller)[1,2], time(), -__LINE__
  1398.   );
  1399.  
  1400.   $self->_data_ses_move_child($child_session, $self);
  1401.  
  1402.   # Test the old parent for garbage.
  1403.   $self->_data_ses_collect_garbage($kr_active_session);
  1404.  
  1405.   # Success!
  1406.   return 1;
  1407. }
  1408.  
  1409. ### Helpful accessors.  -><- Most of these are not documented.
  1410.  
  1411. sub get_active_session {
  1412.   return $kr_active_session;
  1413. }
  1414.  
  1415. sub get_event_count {
  1416.   return $kr_queue->get_item_count();
  1417. }
  1418.  
  1419. sub get_next_event_time {
  1420.   return $kr_queue->get_next_priority();
  1421. }
  1422.  
  1423. #==============================================================================
  1424. # EVENTS
  1425. #==============================================================================
  1426.  
  1427. #------------------------------------------------------------------------------
  1428. # Post an event to the queue.
  1429.  
  1430. sub post {
  1431.   my ($self, $destination, $event_name, @etc) = @_;
  1432.  
  1433.   if (ASSERT_USAGE) {
  1434.     _confess "<us> destination is undefined in post()"
  1435.       unless defined $destination;
  1436.     _confess "<us> event is undefined in post()" unless defined $event_name;
  1437.     _carp(
  1438.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1439.       "effect cannot be achieved by posting it"
  1440.     ) if exists $poes_own_events{$event_name};
  1441.   };
  1442.  
  1443.   # Attempt to resolve the destination session reference against
  1444.   # various things.
  1445.  
  1446.   my $session = $self->_resolve_session($destination);
  1447.   unless (defined $session) {
  1448.     $self->_explain_resolve_failure($destination);
  1449.     return;
  1450.   }
  1451.  
  1452.   # Enqueue the event for "now", which simulates FIFO in our
  1453.   # time-ordered queue.
  1454.  
  1455.   $self->_data_ev_enqueue
  1456.     ( $session, $kr_active_session, $event_name, ET_POST, \@etc,
  1457.       (caller)[1,2], time(),
  1458.     );
  1459.   return 1;
  1460. }
  1461.  
  1462. #------------------------------------------------------------------------------
  1463. # Post an event to the queue for the current session.
  1464.  
  1465. sub yield {
  1466.   my ($self, $event_name, @etc) = @_;
  1467.  
  1468.   if (ASSERT_USAGE) {
  1469.     _confess "<us> event name is undefined in yield()"
  1470.       unless defined $event_name;
  1471.     _carp(
  1472.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1473.       "effect cannot be achieved by yielding it"
  1474.     ) if exists $poes_own_events{$event_name};
  1475.   };
  1476.  
  1477.   $self->_data_ev_enqueue
  1478.     ( $kr_active_session, $kr_active_session, $event_name, ET_POST, \@etc,
  1479.       (caller)[1,2], time(),
  1480.     );
  1481.  
  1482.   undef;
  1483. }
  1484.  
  1485. #------------------------------------------------------------------------------
  1486. # Call an event handler directly.
  1487.  
  1488. sub call {
  1489.   my ($self, $destination, $event_name, @etc) = @_;
  1490.  
  1491.   if (ASSERT_USAGE) {
  1492.     _confess "<us> destination is undefined in call()"
  1493.       unless defined $destination;
  1494.     _confess "<us> event is undefined in call()" unless defined $event_name;
  1495.     _carp(
  1496.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1497.       "effect cannot be achieved by calling it"
  1498.     ) if exists $poes_own_events{$event_name};
  1499.   };
  1500.  
  1501.   # Attempt to resolve the destination session reference against
  1502.   # various things.
  1503.  
  1504.   my $session = $self->_resolve_session($destination);
  1505.   unless (defined $session) {
  1506.     $self->_explain_resolve_failure($destination);
  1507.     return;
  1508.   }
  1509.  
  1510.   # Dispatch the event right now, bypassing the queue altogether.
  1511.   # This tends to be a Bad Thing to Do.
  1512.  
  1513.   # -><- The difference between synchronous and asynchronous events
  1514.   # should be made more clear in the documentation, so that people
  1515.   # have a tendency not to abuse them.  I discovered in xws that that
  1516.   # mixing the two types makes it harder than necessary to write
  1517.   # deterministic programs, but the difficulty can be ameliorated if
  1518.   # programmers set some base rules and stick to them.
  1519.  
  1520.   my $return_value;
  1521.   if (wantarray) {
  1522.     $return_value = [
  1523.       $session == $kr_active_session
  1524.       ? $session->_invoke_state($session, $event_name, \@etc, (caller)[1,2])
  1525.       : $self->_dispatch_event(
  1526.         $session, $kr_active_session,
  1527.         $event_name, ET_CALL, \@etc,
  1528.         (caller)[1,2], time(), -__LINE__
  1529.       )
  1530.     ];
  1531.   }
  1532.   else {
  1533.     $return_value = (
  1534.       $session == $kr_active_session
  1535.       ? $session->_invoke_state($session, $event_name, \@etc, (caller)[1,2])
  1536.       : $self->_dispatch_event(
  1537.         $session, $kr_active_session,
  1538.         $event_name, ET_CALL, \@etc,
  1539.         (caller)[1,2], time(), -__LINE__
  1540.       )
  1541.     );
  1542.   }
  1543.  
  1544.   $! = 0;
  1545.   return @$return_value if wantarray;
  1546.   return $return_value;
  1547. }
  1548.  
  1549. #------------------------------------------------------------------------------
  1550. # Peek at pending alarms.  Returns a list of pending alarms.  This
  1551. # function is deprecated; its lack of documentation is by design.
  1552. # Here's the old POD, in case you're interested.
  1553. #
  1554. # # Return the names of pending timed events.
  1555. # @event_names = $kernel->queue_peek_alarms( );
  1556. #
  1557. # =item queue_peek_alarms
  1558. #
  1559. # queue_peek_alarms() returns a time-ordered list of event names from
  1560. # the current session that have pending timed events.  If a event
  1561. # handler has more than one pending timed event, it will be listed
  1562. # that many times.
  1563. #
  1564. #   my @pending_timed_events = $kernel->queue_peek_alarms();
  1565.  
  1566. sub queue_peek_alarms {
  1567.   my $self = shift;
  1568.  
  1569.   my $alarm_count = $self->_data_ev_get_count_to($kr_active_session);
  1570.  
  1571.   my $my_alarm = sub {
  1572.     return 0 unless $_[0]->[EV_TYPE] & ET_ALARM;
  1573.     return 0 unless $_[0]->[EV_SESSION] == $kr_active_session;
  1574.     return 1;
  1575.   };
  1576.  
  1577.   return( map { $_->[ITEM_PAYLOAD]->[EV_NAME] }
  1578.           $kr_queue->peek_items($my_alarm, $alarm_count)
  1579.         );
  1580. }
  1581.  
  1582. #==============================================================================
  1583. # DELAYED EVENTS
  1584. #==============================================================================
  1585.  
  1586. sub alarm {
  1587.   my ($self, $event_name, $time, @etc) = @_;
  1588.  
  1589.   if (ASSERT_USAGE) {
  1590.     _confess "<us> event name is undefined in alarm()"
  1591.       unless defined $event_name;
  1592.     _carp(
  1593.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1594.       "effect cannot be achieved by setting an alarm for it"
  1595.     ) if exists $poes_own_events{$event_name};
  1596.   };
  1597.  
  1598.   unless (defined $event_name) {
  1599.     $self->_explain_return("invalid parameter to alarm() call");
  1600.     return EINVAL;
  1601.   }
  1602.  
  1603.   $self->_data_ev_clear_alarm_by_name($kr_active_session, $event_name);
  1604.  
  1605.   # Add the new alarm if it includes a time.  Calling _data_ev_enqueue
  1606.   # directly is faster than calling alarm_set to enqueue it.
  1607.   if (defined $time) {
  1608.     $self->_data_ev_enqueue
  1609.       ( $kr_active_session, $kr_active_session,
  1610.         $event_name, ET_ALARM, [ @etc ],
  1611.         (caller)[1,2], $time,
  1612.       );
  1613.   }
  1614.   else {
  1615.     # The event queue has become empty?  Stop the time watcher.
  1616.     $self->loop_pause_time_watcher() unless $kr_queue->get_item_count();
  1617.   }
  1618.  
  1619.   return 0;
  1620. }
  1621.  
  1622. # Add an alarm without clobbering previous alarms of the same name.
  1623. sub alarm_add {
  1624.   my ($self, $event_name, $time, @etc) = @_;
  1625.  
  1626.   if (ASSERT_USAGE) {
  1627.     _confess "<us> undefined event name in alarm_add()"
  1628.       unless defined $event_name;
  1629.     _confess "<us> undefined time in alarm_add()" unless defined $time;
  1630.     _carp(
  1631.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1632.       "effect cannot be achieved by adding an alarm for it"
  1633.     ) if exists $poes_own_events{$event_name};
  1634.   };
  1635.  
  1636.   unless (defined $event_name and defined $time) {
  1637.     $self->_explain_return("invalid parameter to alarm_add() call");
  1638.     return EINVAL;
  1639.   }
  1640.  
  1641.   $self->_data_ev_enqueue
  1642.     ( $kr_active_session, $kr_active_session,
  1643.       $event_name, ET_ALARM, [ @etc ],
  1644.       (caller)[1,2], $time,
  1645.     );
  1646.  
  1647.   return 0;
  1648. }
  1649.  
  1650. # Add a delay, which is just an alarm relative to the current time.
  1651. sub delay {
  1652.   my ($self, $event_name, $delay, @etc) = @_;
  1653.  
  1654.   if (ASSERT_USAGE) {
  1655.     _confess "<us> undefined event name in delay()" unless defined $event_name;
  1656.     _carp(
  1657.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1658.       "effect cannot be achieved by setting a delay for it"
  1659.     ) if exists $poes_own_events{$event_name};
  1660.   };
  1661.  
  1662.   unless (defined $event_name) {
  1663.     $self->_explain_return("invalid parameter to delay() call");
  1664.     return EINVAL;
  1665.   }
  1666.  
  1667.   if (defined $delay) {
  1668.     $self->alarm($event_name, time() + $delay, @etc);
  1669.   }
  1670.   else {
  1671.     $self->alarm($event_name);
  1672.   }
  1673.  
  1674.   return 0;
  1675. }
  1676.  
  1677. # Add a delay without clobbering previous delays of the same name.
  1678. sub delay_add {
  1679.   my ($self, $event_name, $delay, @etc) = @_;
  1680.  
  1681.   if (ASSERT_USAGE) {
  1682.     _confess "<us> undefined event name in delay_add()"
  1683.       unless defined $event_name;
  1684.     _confess "<us> undefined time in delay_add()" unless defined $delay;
  1685.     _carp(
  1686.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1687.       "effect cannot be achieved by adding a delay for it"
  1688.     ) if exists $poes_own_events{$event_name};
  1689.   };
  1690.  
  1691.   unless (defined $event_name and defined $delay) {
  1692.     $self->_explain_return("invalid parameter to delay_add() call");
  1693.     return EINVAL;
  1694.   }
  1695.  
  1696.   $self->alarm_add($event_name, time() + $delay, @etc);
  1697.  
  1698.   return 0;
  1699. }
  1700.  
  1701. #------------------------------------------------------------------------------
  1702. # New style alarms.
  1703.  
  1704. # Set an alarm.  This does more *and* less than plain alarm().  It
  1705. # only sets alarms (that's the less part), but it also returns an
  1706. # alarm ID (that's the more part).
  1707.  
  1708. sub alarm_set {
  1709.   my ($self, $event_name, $time, @etc) = @_;
  1710.  
  1711.   unless (defined $event_name) {
  1712.     $self->_explain_usage("undefined event name in alarm_set()");
  1713.     $! = EINVAL;
  1714.     return;
  1715.   }
  1716.  
  1717.   unless (defined $time) {
  1718.     $self->_explain_usage("undefined time in alarm_set()");
  1719.     $! = EINVAL;
  1720.     return;
  1721.   }
  1722.  
  1723.   if (ASSERT_USAGE) {
  1724.     _carp(
  1725.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1726.       "effect cannot be achieved by setting an alarm for it"
  1727.     ) if exists $poes_own_events{$event_name};
  1728.   }
  1729.  
  1730.   return $self->_data_ev_enqueue
  1731.     ( $kr_active_session, $kr_active_session, $event_name, ET_ALARM, [ @etc ],
  1732.       (caller)[1,2], $time,
  1733.     );
  1734. }
  1735.  
  1736. # Remove an alarm by its ID.  -><- Now that alarms and events have
  1737. # been recombined, this will remove an event by its ID.  However,
  1738. # nothing returns an event ID, so nobody knows what to remove.
  1739.  
  1740. sub alarm_remove {
  1741.   my ($self, $alarm_id) = @_;
  1742.  
  1743.   unless (defined $alarm_id) {
  1744.     $self->_explain_usage("undefined alarm id in alarm_remove()");
  1745.     $! = EINVAL;
  1746.     return;
  1747.   }
  1748.  
  1749.   my ($time, $event) =
  1750.     $self->_data_ev_clear_alarm_by_id($kr_active_session, $alarm_id);
  1751.   return unless defined $time;
  1752.  
  1753.   # In a list context, return the alarm that was removed.  In a scalar
  1754.   # context, return a reference to the alarm that was removed.  In a
  1755.   # void context, return nothing.  Either way this returns a defined
  1756.   # value when someone needs something useful from it.
  1757.  
  1758.   return unless defined wantarray;
  1759.   return ( $event->[EV_NAME], $time, @{$event->[EV_ARGS]} ) if wantarray;
  1760.   return [ $event->[EV_NAME], $time, @{$event->[EV_ARGS]} ];
  1761. }
  1762.  
  1763. # Move an alarm to a new time.  This virtually removes the alarm and
  1764. # re-adds it somewhere else.  In reality, adjust_priority() is
  1765. # optimized for this sort of thing.
  1766.  
  1767. sub alarm_adjust {
  1768.   my ($self, $alarm_id, $delta) = @_;
  1769.  
  1770.   unless (defined $alarm_id) {
  1771.     $self->_explain_usage("undefined alarm id in alarm_adjust()");
  1772.     $! = EINVAL;
  1773.     return;
  1774.   }
  1775.  
  1776.   unless (defined $delta) {
  1777.     $self->_explain_usage("undefined alarm delta in alarm_adjust()");
  1778.     $! = EINVAL;
  1779.     return;
  1780.   }
  1781.  
  1782.   my $my_alarm = sub {
  1783.     $_[0]->[EV_SESSION] == $kr_active_session;
  1784.   };
  1785.   return $kr_queue->adjust_priority($alarm_id, $my_alarm, $delta);
  1786. }
  1787.  
  1788. # A convenient function for setting alarms relative to now.  It also
  1789. # uses whichever time() POE::Kernel can find, which may be
  1790. # Time::HiRes'.
  1791.  
  1792. sub delay_set {
  1793.   my ($self, $event_name, $seconds, @etc) = @_;
  1794.  
  1795.   unless (defined $event_name) {
  1796.     $self->_explain_usage("undefined event name in delay_set()");
  1797.     $! = EINVAL;
  1798.     return;
  1799.   }
  1800.  
  1801.   if (ASSERT_USAGE) {
  1802.     _carp(
  1803.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1804.       "effect cannot be achieved by setting a delay for it"
  1805.     ) if exists $poes_own_events{$event_name};
  1806.   }
  1807.  
  1808.   unless (defined $seconds) {
  1809.     $self->_explain_usage("undefined seconds in delay_set()");
  1810.     $! = EINVAL;
  1811.     return;
  1812.   }
  1813.  
  1814.   return $self->_data_ev_enqueue
  1815.     ( $kr_active_session, $kr_active_session, $event_name, ET_ALARM, [ @etc ],
  1816.       (caller)[1,2], time() + $seconds,
  1817.     );
  1818. }
  1819.  
  1820. # Move a delay to a new offset from time().  As with alarm_adjust(),
  1821. # this is optimized internally for this sort of activity.
  1822.  
  1823. sub delay_adjust {
  1824.   my ($self, $alarm_id, $seconds) = @_;
  1825.  
  1826.   unless (defined $alarm_id) {
  1827.     $self->_explain_usage("undefined delay id in delay_adjust()");
  1828.     $! = EINVAL;
  1829.     return;
  1830.   }
  1831.  
  1832.   unless (defined $seconds) {
  1833.     $self->_explain_usage("undefined delay seconds in delay_abjust()");
  1834.     $! = EINVAL;
  1835.     return;
  1836.   }
  1837.  
  1838.   my $my_delay = sub {
  1839.     $_[0]->[EV_SESSION] == $kr_active_session;
  1840.   };
  1841.   return $kr_queue->set_priority($alarm_id, $my_delay, time() + $seconds);
  1842. }
  1843.  
  1844. # Remove all alarms for the current session.
  1845.  
  1846. sub alarm_remove_all {
  1847.   my $self = shift;
  1848.  
  1849.   # This should never happen, actually.
  1850.   _trap "unknown session in alarm_remove_all call"
  1851.     unless $self->_data_ses_exists($kr_active_session);
  1852.  
  1853.   # Free every alarm owned by the session.  This code is ripped off
  1854.   # from the _stop code to flush everything.
  1855.  
  1856.   my @removed = $self->_data_ev_clear_alarm_by_session($kr_active_session);
  1857.  
  1858.   return unless defined wantarray;
  1859.   return @removed if wantarray;
  1860.   return \@removed;
  1861. }
  1862.  
  1863. #==============================================================================
  1864. # SELECTS
  1865. #==============================================================================
  1866.  
  1867. sub _internal_select {
  1868.   my ($self, $session, $handle, $event_name, $mode) = @_;
  1869.  
  1870.   # If an event is included, then we're defining a filehandle watcher.
  1871.  
  1872.   if ($event_name) {
  1873.     $self->_data_handle_add($handle, $mode, $session, $event_name);
  1874.   }
  1875.   else {
  1876.     $self->_data_handle_remove($handle, $mode, $session);
  1877.   }
  1878. }
  1879.  
  1880. # A higher-level select() that manipulates read, write and expedite
  1881. # selects together.
  1882.  
  1883. sub select {
  1884.   my ($self, $handle, $event_r, $event_w, $event_e) = @_;
  1885.  
  1886.   if (ASSERT_USAGE) {
  1887.     _confess "<us> undefined filehandle in select()" unless defined $handle;
  1888.     _confess "<us> invalid filehandle in select()"
  1889.       unless defined fileno($handle);
  1890.     foreach ($event_r, $event_w, $event_e) {
  1891.       next unless defined $_;
  1892.       _carp(
  1893.         "<us> The '$_' event is one of POE's own.  Its " .
  1894.         "effect cannot be achieved by setting a file watcher to it"
  1895.       ) if exists($poes_own_events{$_});
  1896.     }
  1897.   }
  1898.  
  1899.   $self->_internal_select($kr_active_session, $handle, $event_r, MODE_RD);
  1900.   $self->_internal_select($kr_active_session, $handle, $event_w, MODE_WR);
  1901.   $self->_internal_select($kr_active_session, $handle, $event_e, MODE_EX);
  1902.   return 0;
  1903. }
  1904.  
  1905. # Only manipulate the read select.
  1906. sub select_read {
  1907.   my ($self, $handle, $event_name) = @_;
  1908.  
  1909.   if (ASSERT_USAGE) {
  1910.     _confess "<us> undefined filehandle in select_read()"
  1911.       unless defined $handle;
  1912.     _confess "<us> invalid filehandle in select_read()"
  1913.       unless defined fileno($handle);
  1914.     _carp(
  1915.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1916.       "effect cannot be achieved by setting a file watcher to it"
  1917.     ) if defined($event_name) and exists($poes_own_events{$event_name});
  1918.   };
  1919.  
  1920.   $self->_internal_select($kr_active_session, $handle, $event_name, MODE_RD);
  1921.   return 0;
  1922. }
  1923.  
  1924. # Only manipulate the write select.
  1925. sub select_write {
  1926.   my ($self, $handle, $event_name) = @_;
  1927.  
  1928.   if (ASSERT_USAGE) {
  1929.     _confess "<us> undefined filehandle in select_write()"
  1930.       unless defined $handle;
  1931.     _confess "<us> invalid filehandle in select_write()"
  1932.       unless defined fileno($handle);
  1933.     _carp(
  1934.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1935.       "effect cannot be achieved by setting a file watcher to it"
  1936.     ) if defined($event_name) and exists($poes_own_events{$event_name});
  1937.   };
  1938.  
  1939.   $self->_internal_select($kr_active_session, $handle, $event_name, MODE_WR);
  1940.   return 0;
  1941. }
  1942.  
  1943. # Only manipulate the expedite select.
  1944. sub select_expedite {
  1945.   my ($self, $handle, $event_name) = @_;
  1946.  
  1947.   if (ASSERT_USAGE) {
  1948.     _confess "<us> undefined filehandle in select_expedite()"
  1949.       unless defined $handle;
  1950.     _confess "<us> invalid filehandle in select_expedite()"
  1951.       unless defined fileno($handle);
  1952.     _carp(
  1953.       "<us> The '$event_name' event is one of POE's own.  Its " .
  1954.       "effect cannot be achieved by setting a file watcher to it"
  1955.     ) if defined($event_name) and exists($poes_own_events{$event_name});
  1956.   };
  1957.  
  1958.   $self->_internal_select($kr_active_session, $handle, $event_name, MODE_EX);
  1959.   return 0;
  1960. }
  1961.  
  1962. # Turn off a handle's write mode bit without doing
  1963. # garbage-collection things.
  1964. sub select_pause_write {
  1965.   my ($self, $handle) = @_;
  1966.  
  1967.   if (ASSERT_USAGE) {
  1968.     _confess "<us> undefined filehandle in select_pause_write()"
  1969.       unless defined $handle;
  1970.     _confess "<us> invalid filehandle in select_pause_write()"
  1971.       unless defined fileno($handle);
  1972.   };
  1973.  
  1974.   return 0 unless $self->_data_handle_is_good($handle, MODE_WR);
  1975.  
  1976.   $self->_data_handle_pause($handle, MODE_WR);
  1977.  
  1978.   return 1;
  1979. }
  1980.  
  1981. # Turn on a handle's write mode bit without doing garbage-collection
  1982. # things.
  1983. sub select_resume_write {
  1984.   my ($self, $handle) = @_;
  1985.  
  1986.   if (ASSERT_USAGE) {
  1987.     _confess "<us> undefined filehandle in select_resume_write()"
  1988.       unless defined $handle;
  1989.     _confess "<us> invalid filehandle in select_resume_write()"
  1990.       unless defined fileno($handle);
  1991.   };
  1992.  
  1993.   return 0 unless $self->_data_handle_is_good($handle, MODE_WR);
  1994.  
  1995.   $self->_data_handle_resume($handle, MODE_WR);
  1996.  
  1997.   return 1;
  1998. }
  1999.  
  2000. # Turn off a handle's read mode bit without doing garbage-collection
  2001. # things.
  2002. sub select_pause_read {
  2003.   my ($self, $handle) = @_;
  2004.  
  2005.   if (ASSERT_USAGE) {
  2006.     _confess "<us> undefined filehandle in select_pause_read()"
  2007.       unless defined $handle;
  2008.     _confess "<us> invalid filehandle in select_pause_read()"
  2009.       unless defined fileno($handle);
  2010.   };
  2011.  
  2012.   return 0 unless $self->_data_handle_is_good($handle, MODE_RD);
  2013.  
  2014.   $self->_data_handle_pause($handle, MODE_RD);
  2015.  
  2016.   return 1;
  2017. }
  2018.  
  2019. # Turn on a handle's read mode bit without doing garbage-collection
  2020. # things.
  2021. sub select_resume_read {
  2022.   my ($self, $handle) = @_;
  2023.  
  2024.   if (ASSERT_USAGE) {
  2025.     _confess "<us> undefined filehandle in select_resume_read()"
  2026.       unless defined $handle;
  2027.     _confess "<us> invalid filehandle in select_resume_read()"
  2028.       unless defined fileno($handle);
  2029.   };
  2030.  
  2031.   return 0 unless $self->_data_handle_is_good($handle, MODE_RD);
  2032.  
  2033.   $self->_data_handle_resume($handle, MODE_RD);
  2034.  
  2035.   return 1;
  2036. }
  2037.  
  2038. #==============================================================================
  2039. # Aliases: These functions expose the internal alias accessors with
  2040. # extra fun parameter/return value checking.
  2041. #==============================================================================
  2042.  
  2043. ### Set an alias in the current session.
  2044.  
  2045. sub alias_set {
  2046.   my ($self, $name) = @_;
  2047.  
  2048.   if (ASSERT_USAGE) {
  2049.     _confess "<us> undefined alias in alias_set()" unless defined $name;
  2050.   };
  2051.  
  2052.   # Don't overwrite another session's alias.
  2053.   my $existing_session = $self->_data_alias_resolve($name);
  2054.   if (defined $existing_session) {
  2055.     if ($existing_session != $kr_active_session) {
  2056.       $self->_explain_usage("alias '$name' is in use by another session");
  2057.       return EEXIST;
  2058.     }
  2059.     return 0;
  2060.   }
  2061.  
  2062.   $self->_data_alias_add($kr_active_session, $name);
  2063.   return 0;
  2064. }
  2065.  
  2066. ### Remove an alias from the current session.
  2067.  
  2068. sub alias_remove {
  2069.   my ($self, $name) = @_;
  2070.  
  2071.   if (ASSERT_USAGE) {
  2072.     _confess "<us> undefined alias in alias_remove()" unless defined $name;
  2073.   };
  2074.  
  2075.   my $existing_session = $self->_data_alias_resolve($name);
  2076.  
  2077.   unless (defined $existing_session) {
  2078.     $self->_explain_usage("alias does not exist");
  2079.     return ESRCH;
  2080.   }
  2081.  
  2082.   if ($existing_session != $kr_active_session) {
  2083.     $self->_explain_usage("alias does not belong to current session");
  2084.     return EPERM;
  2085.   }
  2086.  
  2087.   $self->_data_alias_remove($kr_active_session, $name);
  2088.   return 0;
  2089. }
  2090.  
  2091. ### Resolve an alias into a session.
  2092.  
  2093. sub alias_resolve {
  2094.   my ($self, $name) = @_;
  2095.  
  2096.   if (ASSERT_USAGE) {
  2097.     _confess "<us> undefined alias in alias_resolve()" unless defined $name;
  2098.   };
  2099.  
  2100.   my $session = $self->_resolve_session($name);
  2101.   unless (defined $session) {
  2102.     $self->_explain_resolve_failure($name);
  2103.     return;
  2104.   }
  2105.  
  2106.   $session;
  2107. }
  2108.  
  2109. ### List the aliases for a given session.
  2110.  
  2111. sub alias_list {
  2112.   my ($self, $search_session) = @_;
  2113.   my $session =
  2114.     $self->_resolve_session($search_session || $kr_active_session);
  2115.  
  2116.   unless (defined $session) {
  2117.     $self->_explain_resolve_failure($search_session);
  2118.     return;
  2119.   }
  2120.  
  2121.   # Return whatever can be found.
  2122.   my @alias_list = $self->_data_alias_list($session);
  2123.   return wantarray() ? @alias_list : $alias_list[0];
  2124. }
  2125.  
  2126. #==============================================================================
  2127. # Kernel and Session IDs
  2128. #==============================================================================
  2129.  
  2130. # Return the Kernel's "unique" ID.  There's only so much uniqueness
  2131. # available; machines on separate private 10/8 networks may have
  2132. # identical kernel IDs.  The chances of a collision are vanishingly
  2133. # small.
  2134.  
  2135. sub ID {
  2136.   my $self = shift;
  2137.   $self->[KR_ID];
  2138. }
  2139.  
  2140. # Resolve an ID to a session reference.  This function is virtually
  2141. # moot now that _resolve_session does it too.  This explicit call will
  2142. # be faster, though, so it's kept for things that can benefit from it.
  2143.  
  2144. sub ID_id_to_session {
  2145.   my ($self, $id) = @_;
  2146.  
  2147.   if (ASSERT_USAGE) {
  2148.     _confess "<us> undefined ID in ID_id_to_session()" unless defined $id;
  2149.   };
  2150.  
  2151.   my $session = $self->_data_sid_resolve($id);
  2152.   return $session if defined $session;
  2153.  
  2154.   $self->_explain_return("ID does not exist");
  2155.   $! = ESRCH;
  2156.   return;
  2157. }
  2158.  
  2159. # Resolve a session reference to its corresponding ID.
  2160.  
  2161. sub ID_session_to_id {
  2162.   my ($self, $session) = @_;
  2163.  
  2164.   if (ASSERT_USAGE) {
  2165.     _confess "<us> undefined session in ID_session_to_id()"
  2166.       unless defined $session;
  2167.   };
  2168.  
  2169.   my $id = $self->_data_ses_resolve_to_id($session);
  2170.   if (defined $id) {
  2171.     $! = 0;
  2172.     return $id;
  2173.   }
  2174.  
  2175.   $self->_explain_return("session ($session) does not exist");
  2176.   $! = ESRCH;
  2177.   return;
  2178. }
  2179.  
  2180. #==============================================================================
  2181. # Extra reference counts, to keep sessions alive when things occur.
  2182. # They take session IDs because they may be called from resources at
  2183. # times where the session reference is otherwise unknown.
  2184. #==============================================================================
  2185.  
  2186. sub refcount_increment {
  2187.   my ($self, $session_id, $tag) = @_;
  2188.  
  2189.   if (ASSERT_USAGE) {
  2190.     _confess "<us> undefined session ID in refcount_increment()"
  2191.       unless defined $session_id;
  2192.     _confess "<us> undefined reference count tag in refcount_increment()"
  2193.       unless defined $tag;
  2194.   };
  2195.  
  2196.   my $session = $self->ID_id_to_session($session_id);
  2197.   unless (defined $session) {
  2198.     $self->_explain_return("session id $session_id does not exist");
  2199.     $! = ESRCH;
  2200.     return;
  2201.   }
  2202.  
  2203.   my $refcount = $self->_data_extref_inc($session, $tag);
  2204.   # -><- trace it here
  2205.   return $refcount;
  2206. }
  2207.  
  2208. sub refcount_decrement {
  2209.   my ($self, $session_id, $tag) = @_;
  2210.  
  2211.   if (ASSERT_USAGE) {
  2212.     _confess "<us> undefined session ID in refcount_decrement()"
  2213.       unless defined $session_id;
  2214.     _confess "<us> undefined reference count tag in refcount_decrement()"
  2215.       unless defined $tag;
  2216.   };
  2217.  
  2218.   my $session = $self->ID_id_to_session($session_id);
  2219.   unless (defined $session) {
  2220.     $self->_explain_return("session id $session_id does not exist");
  2221.     $! = ESRCH;
  2222.     return;
  2223.   }
  2224.  
  2225.   my $refcount = $self->_data_extref_dec($session, $tag);
  2226.   $self->_data_ses_collect_garbage($session);
  2227.  
  2228.   # trace it here
  2229.   return $refcount;
  2230. }
  2231.  
  2232. #==============================================================================
  2233. # HANDLERS
  2234. #==============================================================================
  2235.  
  2236. # Add or remove event handlers from sessions.
  2237. sub state {
  2238.   my ($self, $event, $state_code, $state_alias) = @_;
  2239.   $state_alias = $event unless defined $state_alias;
  2240.  
  2241.   if (ASSERT_USAGE) {
  2242.     _confess "<us> undefined event name in state()" unless defined $event;
  2243.   };
  2244.  
  2245.   if ( (ref($kr_active_session) ne '') &&
  2246.        (ref($kr_active_session) ne 'POE::Kernel')
  2247.   ) {
  2248.     $kr_active_session->register_state($event, $state_code, $state_alias);
  2249.     return 0;
  2250.   }
  2251.  
  2252.   # -><- A terminal signal (such as UIDESTROY) kills a session.  The
  2253.   # Kernel deallocates the session, which cascades destruction to its
  2254.   # HEAP.  That triggers a Wheel's destruction, which calls
  2255.   # $kernel->state() to remove a state from the session.  The session,
  2256.   # though, is already gone.  If TRACE_RETURNS and/or ASSERT_RETURNS
  2257.   # is set, this causes a warning or fatal error.
  2258.  
  2259.   $self->_explain_return("session ($kr_active_session) does not exist");
  2260.   return ESRCH;
  2261. }
  2262.  
  2263. ###############################################################################
  2264. # Bootstrap the kernel.  This is inherited from a time when multiple
  2265. # kernels could be present in the same Perl process.
  2266. POE::Kernel->new();
  2267. ###############################################################################
  2268. 1;
  2269.  
  2270. __END__
  2271.  
  2272. =head1 NAME
  2273.  
  2274. POE::Kernel - an event driven threaded application kernel in Perl
  2275.  
  2276. =head1 SYNOPSIS
  2277.  
  2278. POE comes with its own event loop, which is based on select() and
  2279. written entirely in Perl.  To use it, simply:
  2280.  
  2281.   use POE;
  2282.  
  2283. POE can adapt itself to work with other event loops and I/O multiplex
  2284. systems.  Currently it adapts to Gtk, Tk, Event.pm, or IO::Poll when
  2285. one of those modules is used before POE::Kernel.
  2286.  
  2287.   use Gtk;  # Or Tk, Event, or IO::Poll;
  2288.   use POE;
  2289.  
  2290. Methods to manage the process' global Kernel instance:
  2291.  
  2292.   # Retrieve the kernel's unique identifier.
  2293.   $kernel_id = $kernel->ID;
  2294.  
  2295.   # Run the event loop, only returning when it has no more sessions to
  2296.   # dispatch events to.  Supports two forms.
  2297.   $poe_kernel->run();
  2298.   POE::Kernel->run();
  2299.  
  2300. FIFO event methods:
  2301.  
  2302.   # Post an event to an arbitrary session.
  2303.   $kernel->post( $session, $event, @event_args );
  2304.  
  2305.   # Post an event back to the current session.
  2306.   $kernel->yield( $event, @event_args );
  2307.  
  2308.   # Call an event handler synchronously.  Bypasses POE's event queue
  2309.   # and returns the handler's return value.
  2310.   $handler_result = $kernel->call( $session, $event, @event_args );
  2311.  
  2312. Original alarm and delay methods:
  2313.  
  2314.   # Post an event which will be delivered at a given Unix epoch time.
  2315.   # This clears previous timed events with the same state name.
  2316.   $kernel->alarm( $event, $epoch_time, @event_args );
  2317.  
  2318.   # Post an additional alarm, leaving existing ones in the queue.
  2319.   $kernel->alarm_add( $event, $epoch_time, @event_args );
  2320.  
  2321.   # Post an event which will be delivered after a delay, specified in
  2322.   # seconds hence. This clears previous timed events with the same
  2323.   # name.
  2324.   $kernel->delay( $event, $seconds, @event_args );
  2325.  
  2326.   # Post an additional delay, leaving existing ones in the queue.
  2327.   $kernel->delay_add( $event, $seconds, @event_args );
  2328.  
  2329. June 2001 alarm and delay methods:
  2330.  
  2331.   # Post an event which will be delivered at a given Unix epoch
  2332.   # time. This does not clear previous events with the same name.
  2333.   $alarm_id = $kernel->alarm_set( $event, $epoch_time, @etc );
  2334.  
  2335.   # Post an event which will be delivered a number of seconds hence.
  2336.   # This does not clear previous events with the same name.
  2337.   $alarm_id = $kernel->delay_set( $event, $seconds_hence, @etc );
  2338.  
  2339.   # Adjust an existing alarm by a number of seconds.
  2340.   $kernel->alarm_adjust( $alarm_id, $number_of_seconds );
  2341.  
  2342.   # Refresh an existing delay to a number of seconds in the future.
  2343.   $kernel->delay_adjust( $delay_id, $number_of_seconds_hence );
  2344.  
  2345.   # Remove a specific alarm, regardless whether it shares a name with
  2346.   # others.
  2347.   $kernel->alarm_remove( $alarm_id );
  2348.  
  2349.   # Remove all alarms for the current session.
  2350.   #kernel->alarm_remove_all( );
  2351.  
  2352. Symbolic name, or session alias methods:
  2353.  
  2354.   # Set an alias for the current session.
  2355.   $status = $kernel->alias_set( $alias );
  2356.  
  2357.   # Clear an alias for the current session:
  2358.   $status = $kernel->alias_remove( $alias );
  2359.  
  2360.   # Resolve an alias into a session reference.  Most POE::Kernel
  2361.   # methods do this for you.
  2362.   $session_reference = $kernel->alias_resolve( $alias );
  2363.  
  2364.   # Resolve a session ID to a session reference.  The alias_resolve
  2365.   # method does this as well, but this is faster.
  2366.   $session_reference = $kernel->ID_id_to_session( $session_id );
  2367.  
  2368.   # Return a session ID for a session reference.  It is functionally
  2369.   # equivalent to $session->ID.
  2370.   $session_id = $kernel->ID_session_to_id( $session_reference );
  2371.  
  2372.   # Return a list of aliases for a session (or the current one, by
  2373.   # default).
  2374.   @aliases = $kernel->alias_list( $session );
  2375.  
  2376. Filehandle watcher methods:
  2377.  
  2378.   # Watch for read readiness on a filehandle.
  2379.   $kernel->select_read( $file_handle, $event );
  2380.  
  2381.   # Stop watching a filehandle for read-readiness.
  2382.   $kernel->select_read( $file_handle );
  2383.  
  2384.   # Watch for write readiness on a filehandle.
  2385.   $kernel->select_write( $file_handle, $event );
  2386.  
  2387.   # Stop watching a filehandle for write-readiness.
  2388.   $kernel->select_write( $file_handle );
  2389.  
  2390.   # Pause and resume write readiness watching.  These have lower
  2391.   # overhead than full select_write() calls.
  2392.   $kernel->select_pause_write( $file_handle );
  2393.   $kernel->select_resume_write( $file_handle );
  2394.  
  2395.   # Pause and resume read readiness watching.  These have lower
  2396.   # overhead than full select_read() calls.
  2397.   $kernel->select_pause_read( $file_handle );
  2398.   $kernel->select_resume_read( $file_handle );
  2399.  
  2400.   # Watch for out-of-bound (expedited) read readiness on a filehandle.
  2401.   $kernel->select_expedite( $file_handle, $event );
  2402.  
  2403.   # Stop watching a filehandle for out-of-bound data.
  2404.   $kernel->select_expedite( $file_handle );
  2405.  
  2406.   # Set and/or clear a combination of selects in one call.
  2407.   $kernel->select( $file_handle,
  2408.                    $read_event,     # or undef to clear it
  2409.                    $write_event,    # or undef to clear it
  2410.                    $expedite_event, # or undef to clear it
  2411.                  );
  2412.  
  2413. Signal watcher and generator methods:
  2414.  
  2415.   # Watch for a signal, and generate an event when it arrives.
  2416.   $kernel->sig( $signal_name, $event );
  2417.  
  2418.   # Stop watching for a signal.
  2419.   $kernel->sig( $signal_name );
  2420.  
  2421.   # Handle a signal, preventing the program from terminating.
  2422.   $kernel->sig_handled();
  2423.  
  2424.   # Post a signal through POE rather than through the underlying OS.
  2425.   # This only works within the same process.
  2426.   $kernel->signal( $session, $signal_name, @optional_args );
  2427.  
  2428. State (event handler) management methods:
  2429.  
  2430.   # Remove an existing handler from the current Session.
  2431.   $kernel->state( $event_name );
  2432.  
  2433.   # Add a new inline handler, or replace an existing one.
  2434.   $kernel->state( $event_name, $code_reference );
  2435.  
  2436.   # Add a new object or package handler, or replace an existing
  2437.   # one. The object method will be the same as the eventname.
  2438.   $kernel->state( $event_name, $object_ref_or_package_name );
  2439.  
  2440.   # Add a new object or package handler, or replace an existing
  2441.   # one. The object method may be different from the event name.
  2442.   $kernel->state( $event_name, $object_ref_or_package_name, $method_name );
  2443.  
  2444. External reference count methods:
  2445.  
  2446.   # Increment a session's external reference count.
  2447.   $kernel->refcount_increment( $session_id, $refcount_name );
  2448.  
  2449.   # Decrement a session's external reference count.
  2450.   $kernel->refcount_decrement( $session_id, $refcount_name );
  2451.  
  2452. Kernel data accessors:
  2453.  
  2454.   # Return a reference to the currently active session, or to the
  2455.   # kernel if called outside any session.
  2456.   $session = $kernel->get_active_session();
  2457.  
  2458. Exported symbols:
  2459.  
  2460.   # A reference to the global POE::Kernel instance.
  2461.   $poe_kernel
  2462.  
  2463.   # Some graphical toolkits (Tk) require at least one active widget in
  2464.   # order to use their event loops.  POE allocates a main window so it
  2465.   # can function when using one of these toolkits.
  2466.   $poe_main_window
  2467.  
  2468. =head1 DESCRIPTION
  2469.  
  2470. POE::Kernel is an event application kernel.  It provides a
  2471. lightweight, cooperatively-timesliced process model in addition to the
  2472. usual basic event loop functions.
  2473.  
  2474. POE::Kernel cooperates with three external event loops.  This is
  2475. discussed after the public methods are described.
  2476.  
  2477. The POE manpage describes a shortcut for using several POE modules at
  2478. once.  It also includes a complete sample program with a brief
  2479. walkthrough of its parts.
  2480.  
  2481. =head1 PUBLIC KERNEL METHODS
  2482.  
  2483. This section discusses in more detail the POE::Kernel methods that
  2484. appear in the SYNOPSIS.
  2485.  
  2486. =head2 Kernel Management and Data Accessors
  2487.  
  2488. These functions manipulate the Kernel itself or retrieve information
  2489. from it.
  2490.  
  2491. =over 2
  2492.  
  2493. =item ID
  2494.  
  2495. ID() returns the kernel's unique identifier.
  2496.  
  2497.   print "The currently running Kernel is: $kernel->ID\n";
  2498.  
  2499. Every POE::Kernel instance is assigned an ID at birth.  This ID tries
  2500. to differentiate any given instance from all the others, even if they
  2501. exist on the same machine.  The ID is a hash of the machine's name and
  2502. the kernel's instantiation time and process ID.
  2503.  
  2504.   ~/perl/poe$ perl -wl -MPOE -e 'print $poe_kernel->ID'
  2505.   rocco.homenet-39240c97000001d8
  2506.  
  2507. =item run
  2508.  
  2509. run() starts the kernel's event loop.  It returns only after every
  2510. session has stopped, or immediately if no sessions have yet been
  2511. started.
  2512.  
  2513.   #!/usr/bin/perl -w
  2514.   use strict;
  2515.   use POE;
  2516.  
  2517.   # ... start bootstrap session(s) ...
  2518.  
  2519.   $poe_kernel->run();
  2520.   exit;
  2521.  
  2522. The run() method may be called on an instance of POE::Kernel.
  2523.  
  2524.   my $kernel = POE::Kernel->new();
  2525.   $kernel->run();
  2526.  
  2527. It may also be called as class method.
  2528.  
  2529.   POE::Kernel->run();
  2530.  
  2531. The run() method does not return a meaningful value.
  2532.  
  2533. =item run_one_timeslice
  2534.  
  2535. run_one_timeslice() checks for new events, which are enqueued, then
  2536. dispatches any events that were due at the time it was called.  Then
  2537. it returns.
  2538.  
  2539. It is often used to emulate blocking behavior for procedural code.
  2540.  
  2541.   my $done = 0;
  2542.  
  2543.   sub handle_some_event {
  2544.     $done = 1;
  2545.   }
  2546.  
  2547.   while (not $done) {
  2548.     $kernel->run_one_timeslice();
  2549.   }
  2550.  
  2551. Note: The above example will "spin" if POE::Kernel is done but $done
  2552. isn't set.
  2553.  
  2554. =item stop
  2555.  
  2556. stop() forcibly stops the kernel.  The event queue is emptied, all
  2557. resources are released, and all sessions are deallocated.
  2558. POE::Kernel's run() method returns as if everything ended normally,
  2559. which is a lie.
  2560.  
  2561. B<This function has a couple serious caveats.  Use it with caution.>
  2562.  
  2563. The session running when stop() is called will not fully destruct
  2564. until it returns.  If you think about it, there's at least a reference
  2565. to the session in its call stack, plus POE::Kernel is holding onto at
  2566. least one reference so it can invoke the session.
  2567.  
  2568. Sessions are not notified about their destruction.  If anything relies
  2569. on _stop being delivered, it will break and/or leak memory.
  2570.  
  2571. stop() has been added as an B<experimental> function to support
  2572. forking child kernels with POE::Wheel::Run.  We may remove it without
  2573. notice if it becomes really icky.  If you have good uses for it,
  2574. please mention them on POE's mailing list.
  2575.  
  2576. =back
  2577.  
  2578. =head2 FIFO Event Methods
  2579.  
  2580. FIFO events are dispatched in the order in which they were queued.
  2581. These methods queue new FIFO events.  A session will not spontaneously
  2582. stop as long as it has at least one FIFO event in the queue.
  2583.  
  2584. =over 2
  2585.  
  2586. =item post SESSION, EVENT_NAME, PARAMETER_LIST
  2587.  
  2588. =item post SESSION, EVENT_NAME
  2589.  
  2590. post() enqueues an event to be dispatched to EVENT_NAME in SESSION.
  2591. If a PARAMETER_LIST is included, its values will be passed as
  2592. arguments to EVENT_NAME's handler.
  2593.  
  2594.   $_[KERNEL]->post( $session, 'do_this' );
  2595.   $_[KERNEL]->post( $session, 'do_that', $with_this, $and_this );
  2596.   $_[KERNEL]->post( $session, 'do_that', @with_these );
  2597.  
  2598.   POE::Session->new(
  2599.     do_this => sub { print "do_this called with $_[ARG0] and $_[ARG1]\n" },
  2600.     do_that => sub { print "do_that called with @_[ARG0..$#_]\n" },
  2601.   );
  2602.  
  2603. The post() method returns a boolean value indicating whether the event
  2604. was enqueued successfully.  $! will explain why the post() failed:
  2605.  
  2606. ESRCH: The SESSION did not exist at the time of the post() call.
  2607.  
  2608. Posted events keep both the sending and receiving session alive until
  2609. they're dispatched.
  2610.  
  2611. =item yield EVENT_NAME, PARAMETER_LIST
  2612.  
  2613. =item yield EVENT_NAME
  2614.  
  2615. yield() enqueues an EVENT_NAME event for the session that calls it.
  2616. If a PARAMETER_LIST is included, its values will be passed as
  2617. arguments to EVENT_NAME's handler.
  2618.  
  2619. yield() is shorthand for post() where the event's destination is the
  2620. current session.
  2621.  
  2622. Events posted with yield() must propagate through POE's FIFO before
  2623. they're dispatched.  This effectively yields timeslices to other
  2624. sessions which have events enqueued before it.
  2625.  
  2626.   $kernel->yield( 'do_this' );
  2627.   $kernel->yield( 'do_that', @with_these );
  2628.  
  2629. The previous yield() calls are equivalent to these post() calls.
  2630.  
  2631.   $kernel->post( $session, 'do_this' );
  2632.   $kernel->post( $session, 'do_that', @with_these );
  2633.  
  2634. The yield() method does not return a meaningful value.
  2635.  
  2636. =back
  2637.  
  2638. =head2 Synchronous Events
  2639.  
  2640. Sometimes it's necessary to invoke an event handler right away, for
  2641. example to handle a time-critical external event that would be spoiled
  2642. by the time an event propagated through POE's FIFO.  The kernel's
  2643. call() method provides for time-critical events.
  2644.  
  2645. =over 2
  2646.  
  2647. =item call SESSION, EVENT_NAME, PARAMETER_LIST
  2648.  
  2649. =item call SESSION, EVENT_NAME
  2650.  
  2651. call() bypasses the FIFO to call EVENT_NAME in a SESSION, optionally
  2652. with values from a PARAMETER_LIST.  The values will be passed as
  2653. arguments to EVENT_NAME at dispatch time.
  2654.  
  2655. call() returns whatever EVENT_NAME's handler does.  The call() call's
  2656. status is returned in $!, which is 0 for success or a nonzero reason
  2657. for failure.
  2658.  
  2659.   $return_value = $kernel->call( 'do_this_now' );
  2660.   die "could not do_this_now: $!" if $!;
  2661.  
  2662. POE uses call() to dispatch some resource events without FIFO latency.
  2663. Filehandle watchers, for example, would continue noticing a handle's
  2664. readiness until it was serviced by a handler.  This could result in
  2665. several redundant readiness events being enqueued before the first one
  2666. was dispatched.
  2667.  
  2668. Reasons why call() might fail:
  2669.  
  2670. ESRCH: The SESSION did not exist at the time call() was called.
  2671.  
  2672. =back
  2673.  
  2674. =head2 Delayed Events (Original Interface)
  2675.  
  2676. POE also manages timed events.  These are events that should be
  2677. dispatched after at a certain time or after some time has elapsed.  A
  2678. session will not spontaneously stop as long as it has at least one
  2679. pending timed event.  Alarms and delays always are enqueued for the
  2680. current session, so a SESSION parameter is not needed.
  2681.  
  2682. The kernel manages two types of timed event.  Alarms are set to be
  2683. dispatched at a particular time, and delays are set to go off after a
  2684. certain interval.
  2685.  
  2686. If Time::HiRes is installed, POE::Kernel will use it to increase the
  2687. accuracy of timed events.  The kernel will use the less accurate
  2688. built-in time() if Time::HiRes isn't available.
  2689.  
  2690. If the use of Time::HiRes is not desired, for whatever reason, it can
  2691. be disabled like so:
  2692.  
  2693.     sub POE::Kernel::USE_TIME_HIRES () { 0 }
  2694.     use POE;
  2695.  
  2696. =over 2
  2697.  
  2698. =item alarm EVENT_NAME, EPOCH_TIME, PARAMETER_LIST
  2699.  
  2700. =item alarm EVENT_NAME, EPOCH_TIME
  2701.  
  2702. =item alarm EVENT_NAME
  2703.  
  2704. POE::Kernel's alarm() is a single-shot alarm.  It first clears all the
  2705. timed events destined for EVENT_NAME in the current session.  It then
  2706. may set a new alarm for EVENT_NAME if EPOCH_TIME is included,
  2707. optionally including values from a PARAMETER_LIST.
  2708.  
  2709. It is possible to post an alarm with an EPOCH_TIME in the past; in
  2710. that case, it will be placed towards the front of the event queue.
  2711.  
  2712. To clear existing timed events for 'do_this' and set a new alarm with
  2713. parameters:
  2714.  
  2715.   $kernel->alarm( 'do_this', $at_this_time, @with_these_parameters );
  2716.  
  2717. Clear existing timed events for 'do_that' and set a new alarm without
  2718. parameters:
  2719.  
  2720.   $kernel->alarm( 'do_that', $at_this_time );
  2721.  
  2722. To clear existing timed events for 'do_the_other_thing' without
  2723. setting a new delay:
  2724.  
  2725.   $kernel->alarm( 'do_the_other_thing' );
  2726.  
  2727. This method will clear all types of alarms without regard to how they
  2728. were set.
  2729.  
  2730. POE::Kernel's alarm() returns 0 on success or EINVAL if EVENT_NAME is
  2731. not defined.
  2732.  
  2733. =item alarm_add EVENT_NAME, EPOCH_TIME, PARAMETER_LIST
  2734.  
  2735. =item alarm_add EVENT_NAME, EPOCH_TIME
  2736.  
  2737. alarm_add() sets an additional timed event for EVENT_NAME in the
  2738. current session without clearing pending timed events.  The new alarm
  2739. event will be dispatched no earlier than EPOCH_TIME.
  2740.  
  2741. To enqueue additional alarms for 'do_this':
  2742.  
  2743.   $kernel->alarm_add( 'do_this', $at_this_time, @with_these_parameters );
  2744.   $kernel->alarm_add( 'do_this', $at_this_time );
  2745.  
  2746. Additional alarms can be cleared with POE::Kernel's alarm() method.
  2747.  
  2748. alarm_add() returns 0 on success or EINVAL if EVENT_NAME or EPOCH_TIME
  2749. is undefined.
  2750.  
  2751. =item delay EVENT_NAME, SECONDS, PARAMETER_LIST
  2752.  
  2753. =item delay EVENT_NAME, SECONDS
  2754.  
  2755. =item delay EVENT_NAME
  2756.  
  2757. delay() is a single-shot delayed event.  It first clears all the timed
  2758. events destined for EVENT_NAME in the current session.  If SECONDS is
  2759. included, it will set a new delay for EVENT_NAME to be dispatched
  2760. SECONDS seconds hence, optionally including values from a
  2761. PARAMETER_LIST.  Please note that delay()ed event are placed on the
  2762. queue and are thus asynchronous.
  2763.  
  2764. delay() uses whichever time(2) is available within POE::Kernel.  That
  2765. may be the more accurate Time::HiRes::time(), or perhaps not.
  2766. Regardless, delay() will do the right thing without sessions testing
  2767. for Time::HiRes themselves.
  2768.  
  2769. It's possible to post delays with negative SECONDS; in those cases,
  2770. they will be placed towards the front of the event queue.
  2771.  
  2772. To clear existing timed events for 'do_this' and set a new delay with
  2773. parameters:
  2774.  
  2775.   $kernel->delay( 'do_this', $after_this_much_time, @with_these );
  2776.  
  2777. Clear existing timed events for 'do_that' and set a new delay without
  2778. parameters:
  2779.  
  2780.   $kernel->delay( 'do_this', $after_this_much_time );
  2781.  
  2782. To clear existing timed events for 'do_the_other_thing' without
  2783. setting a new delay:
  2784.  
  2785.   $kernel->delay( 'do_the_other_thing' );
  2786.  
  2787. C<delay()> returns 0 on success or a reason for its failure: EINVAL if
  2788. EVENT_NAME is undefined.
  2789.  
  2790. =item delay_add EVENT_NAME, SECONDS, PARAMETER_LIST
  2791.  
  2792. =item delay_add EVENT_NAME, SECONDS
  2793.  
  2794. delay_add() sets an additional delay for EVENT_NAME in the current
  2795. session without clearing pending timed events.  The new delay will be
  2796. dispatched no sooner than SECONDS seconds hence.
  2797.  
  2798. To enqueue additional delays for 'do_this':
  2799.  
  2800.   $kernel->delay_add( 'do_this', $after_this_much_time, @with_these );
  2801.   $kernel->delay_add( 'do_this', $after_this_much_time );
  2802.  
  2803. Additional alarms cas be cleared with POE::Kernel's delay() method.
  2804.  
  2805. delay_add() returns 0 on success or a reason for failure: EINVAL if
  2806. EVENT_NAME or SECONDS is undefined.
  2807.  
  2808. =back
  2809.  
  2810. =head2 Delayed Events (June 2001 Interface)
  2811.  
  2812. These functions were finally added in June of 2001.  They manage
  2813. alarms and delays by unique IDs, allowing existing alarms to be moved
  2814. around, added, and removed with greater accuracy than the original
  2815. interface.
  2816.  
  2817. The June 2001 interface provides a different set of functions for
  2818. alarms, but their underlying semantics are the same.  Foremost, they
  2819. are always set for the current session.  That's why they don't require
  2820. a SESSION parameter.
  2821.  
  2822. For more information, see the previous section about the older alarms
  2823. interface.
  2824.  
  2825. =over 2
  2826.  
  2827. =item alarm_adjust ALARM_ID, DELTA
  2828.  
  2829. alarm_adjust adjusts an existing alarm by a number of seconds, the
  2830. DELTA, which may be positive or negative.  On success, it returns the
  2831. new absolute alarm time.
  2832.  
  2833.   # Move the alarm 10 seconds back in time.
  2834.   $new_time = $kernel->alarm_adjust( $alarm_id, -10 );
  2835.  
  2836. On failure, it returns false and sets $! to a reason for the failure.
  2837. That may be EINVAL if the alarm ID or the delta are bad values.  It
  2838. could also be ESRCH if the alarm doesn't exist (perhaps it already was
  2839. dispatched).  $! may also contain EPERM if the alarm doesn't belong to
  2840. the session trying to adjust it.
  2841.  
  2842. =item alarm_set EVENT_NAME, TIME, PARAMETER_LIST
  2843.  
  2844. =item alarm_set EVENT_NAME, TIME
  2845.  
  2846. Sets an alarm.  This differs from POE::Kernel's alarm() in that it
  2847. lets programs set alarms without clearing them.  Furthermore, it
  2848. returns an alarm ID which can be used in other new-style alarm
  2849. functions.
  2850.  
  2851.   $alarm_id = $kernel->alarm_set( party => 1000000000 )
  2852.   $kernel->alarm_remove( $alarm_id );
  2853.  
  2854. alarm_set sets $! and returns false if it fails.  $! will be EINVAL if
  2855. one of the function's parameters is bogus.
  2856.  
  2857. See: alarm_remove,
  2858.  
  2859. =item alarm_remove ALARM_ID
  2860.  
  2861. Removes an alarm from the current session, but first you must know its
  2862. ID.  The ID comes from a previous alarm_set() call, or you could hunt
  2863. at random for alarms to remove.
  2864.  
  2865. Upon success, alarm_remove() returns something true based on its
  2866. context.  In a list context, it returns three things: The removed
  2867. alarm's event name, its scheduled time, and a reference to the list of
  2868. parameters that were included with it.  This is all you need to
  2869. re-schedule the alarm later.
  2870.  
  2871.   my @old_alarm_list = $kernel->alarm_remove( $alarm_id );
  2872.   if (@old_alarm_list) {
  2873.     print "Old alarm event name: $old_alarm_list[0]\n";
  2874.     print "Old alarm time      : $old_alarm_list[1]\n";
  2875.     print "Old alarm parameters: @{$old_alarm_list[2]}\n";
  2876.   }
  2877.   else {
  2878.     print "Could not remove alarm $alarm_id: $!\n";
  2879.   }
  2880.  
  2881. In a scalar context, it returns a reference to a list of the three
  2882. things above.
  2883.  
  2884.   my $old_alarm_scalar = $kernel->alarm_remove( $alarm_id );
  2885.   if ($old_alarm_scalar) {
  2886.     print "Old alarm event name: $old_alarm_scalar->[0]\n";
  2887.     print "Old alarm time      : $old_alarm_scalar->[1]\n";
  2888.     print "Old alarm parameters: @{$old_alarm_scalar->[2]}\n";
  2889.   }
  2890.   else {
  2891.     print "Could not remove alarm $alarm_id: $!\n";
  2892.   }
  2893.  
  2894. Upon failure, it returns false and sets $! to the reason it failed.
  2895. $! may be EINVAL if the alarm ID is undefined, or it could be ESRCH if
  2896. no alarm was found by that ID.  It may also be EPERM if some other
  2897. session owns that alarm.
  2898.  
  2899. =item alarm_remove_all
  2900.  
  2901. alarm_remove_all() removes all alarms from the current session.  It
  2902. obviates the need for queue_peek_alarms(), which has been deprecated.
  2903.  
  2904. This function takes no arguments.  In scalar context, it returns a
  2905. reference to a list of alarms that were removed.  In list context, it
  2906. returns the list of removed alarms themselves.
  2907.  
  2908. Each removed alarm follows the same format as in alarm_remove().
  2909.  
  2910.   my @removed_alarms = $kernel->alarm_remove_all( );
  2911.   foreach my $alarm (@removed_alarms) {
  2912.     print "-----\n";
  2913.     print "Removed alarm event name: $alarm->[0]\n";
  2914.     print "Removed alarm time      : $alarm->[1]\n";
  2915.     print "Removed alarm parameters: @{$alarm->[2]}\n";
  2916.   }
  2917.  
  2918.   my $removed_alarms = $kernel->alarm_remove_all( );
  2919.   foreach my $alarm (@$removed_alarms) {
  2920.     ...;
  2921.   }
  2922.  
  2923. =item delay_set EVENT_NAME, SECONDS, PARAMETER_LIST
  2924.  
  2925. =item delay_set EVENT_NAME, SECONDS
  2926.  
  2927. delay_set() is a handy way to set alarms for a number of seconds
  2928. hence.  Its EVENT_NAME and PARAMETER_LIST are the same as for
  2929. alarm_set, and it returns the same things as alarm_set, both as a
  2930. result of success and of failure.
  2931.  
  2932. It's only difference is that SECONDS is added to the current time to
  2933. get the time the delay will be dispatched.  It uses whichever time()
  2934. POE::Kernel does, which may be Time::HiRes' high-resolution timer, if
  2935. that's available.
  2936.  
  2937. =item delay_adjust DELAY_ID, SECONDS
  2938.  
  2939. delay_adjust adjusts an existing delay to be a number of seconds in
  2940. the future.  It is useful for refreshing watchdog timers, for
  2941. instance.
  2942.  
  2943.   # Refresh a delay for 10 seconds into the future.
  2944.   $new_time = $kernel->delay_adjust( $delay_id, 10 );
  2945.  
  2946. On failure, it returns false and sets $! to a reason for the failure.
  2947. That may be EINVAL if the delay ID or the seconds are bad values.  It
  2948. could also be ESRCH if the delay doesn't exist (perhaps it already was
  2949. dispatched).  $! may also contain EPERM if the delay doesn't belong to
  2950. the session trying to adjust it.
  2951.  
  2952. =back
  2953.  
  2954. =head2 Numeric Session IDs and Symbolic Session Names (Aliases)
  2955.  
  2956. Every session is given a unique ID at birth.  This ID combined with
  2957. the kernel's own ID can uniquely identify a particular session
  2958. anywhere in the world.
  2959.  
  2960. Sessions can also use the kernel's alias dictionary to give themselves
  2961. symbolic names.  Once a session has a name, it may be referred to by
  2962. that name wherever a kernel method expects a session reference or ID.
  2963.  
  2964. Sessions with aliases are treated as daemons within the current
  2965. program (servlets?).  They are kept alive even without other things to
  2966. do on the assumption that some other session will need their services.
  2967.  
  2968. Daemonized sessions may spontaneously self-destruct if no other
  2969. sessions are active.  This prevents "zombie" servlets from keeping a
  2970. program running with nothing to do.
  2971.  
  2972. =over 2
  2973.  
  2974. =item alias_set ALIAS
  2975.  
  2976. alias_set() sets an ALIAS for the current session.  The ALIAS may then
  2977. be used nearly everywhere a session reference or ID is expected.
  2978. Sessions may have more than one alias, and each must be defined in a
  2979. separate alias_set() call.
  2980.  
  2981.   $kernel->alias_set( 'ishmael' ); # o/` A name I call myself. o/`
  2982.  
  2983. Aliases allow sessions to stay alive even when they may have nothing
  2984. to do.  Sessions can use them to become autonomous services that other
  2985. sessions refer to by name.
  2986.  
  2987. Aliases keep sessions alive as long as the program has work to do.  If
  2988. a program's remaining sessions are being kept alive solely by aliases,
  2989. they will be terminated.  This prevents running, the remaining
  2990. sessions will be terminated.  This prevents deadlocks where two or
  2991. more sessions are idly waiting for events from each other.
  2992.  
  2993.   $kernel->alias_set( 'httpd' );
  2994.   $kernel->post( httpd => set_handler => $uri_regexp => 'callback_event' );
  2995.  
  2996. alias_set() returns 0 on success, or a nonzero failure indicator:
  2997.  
  2998. =over 2
  2999.  
  3000. =item EEXIST
  3001.  
  3002. The alias already is assigned to a different session.
  3003.  
  3004. =back
  3005.  
  3006. =item alias_remove ALIAS
  3007.  
  3008. alias_remove() clears an existing ALIAS from the current session.  The
  3009. ALIAS will no longer refer to this session, and some other session may
  3010. claim it.
  3011.  
  3012.   $kernel->alias_remove( 'Shirley' ); # And don't call me Shirley.
  3013.  
  3014. If a session is only being kept alive by its aliases, it will stop
  3015. once they are removed.
  3016.  
  3017. alias_remove() returns 0 on success or a reason for its failure:
  3018.  
  3019. ESRCH: The Kernel's dictionary does not include the ALIAS being
  3020. removed.
  3021.  
  3022. EPERM: ALIAS belongs to some other session, and the current one does
  3023. not have the authority to clear it.
  3024.  
  3025. =item alias_resolve ALIAS
  3026.  
  3027. alias_resolve() returns a session reference corresponding to its given
  3028. ALIAS.  This method has been overloaded over time, and now ALIAS may
  3029. be several things:
  3030.  
  3031. An alias:
  3032.  
  3033.   $session_reference = $kernel->alias_resolve( 'irc_component' );
  3034.  
  3035. A stringified session reference.  This is a form of weak reference:
  3036.  
  3037.   $blessed_session_reference = $kernel->alias_resolve( "$stringified_one" );
  3038.  
  3039. A numeric session ID:
  3040.  
  3041.   $session_reference = $kernel->alias_resolve( $session_id );
  3042.  
  3043. alias_resolve() returns undef upon failure, setting $! to explain the
  3044. error:
  3045.  
  3046. ESRCH: The Kernel's dictionary does not include ALIAS.
  3047.  
  3048. These functions work directly with session IDs.  They are faster than
  3049. alias_resolve() in the specific cases where they're useful.
  3050.  
  3051. =item ID_id_to_session SESSION_ID
  3052.  
  3053. ID_id_to_session() returns a session reference for a given numeric
  3054. session ID.
  3055.  
  3056.   $session_reference = ID_id_to_session( $session_id );
  3057.  
  3058. It returns undef if a lookup fails, and it sets $! to explain why the
  3059. lookup failed:
  3060.  
  3061. ESRCH: The session ID does not refer to a running session.
  3062.  
  3063. =item alias_list SESSION
  3064.  
  3065. =item alias_list
  3066.  
  3067. alias_list() returns a list of alias(es) associated with a SESSION, or
  3068. with the current session if a SESSION is omitted.
  3069.  
  3070. SESSION may be a session reference (either blessed or stringified), a
  3071. session ID, or a session alias.  It will be resolved into a session
  3072. reference internally, and that will be used to locate the session's
  3073. aliases.
  3074.  
  3075. alias_list() returns a list of aliases associated with the session.
  3076. It returns an empty list if none were found.
  3077.  
  3078. =item ID_session_to_id SESSION_REFERENCE
  3079.  
  3080. ID_session_to_id() returns the ID associated with a session reference.
  3081. This is virtually identical to SESSION_REFERENCE->ID, except that
  3082. SESSION_REFERENCE may have been stringified.  For example, this will
  3083. work, provided that the session exists:
  3084.  
  3085.   $session_id = ID_session_to_id( "$session_reference" );
  3086.  
  3087. ID_session_to_id() returns undef if a lookup fails, and it sets $! to
  3088. explain why the lookup failed.
  3089.  
  3090. ESRCH: The session reference does not describe a session which is
  3091. currently running.
  3092.  
  3093. =back
  3094.  
  3095. =head2 Filehandle Watcher Methods (Selects)
  3096.  
  3097. Filehandle watchers emit events when files become available to be read
  3098. from or written to.  As of POE 0.1702 these events are queued along
  3099. with all the rest.  They are no longer "synchronous" or "immediate".
  3100.  
  3101. Filehandle watchers are often called "selects" in POE because they
  3102. were originally implemented with the select(2) I/O multiplexing
  3103. function.
  3104.  
  3105. File I/O event handlers are expected to interact with filehandles in a
  3106. way that causes them to stop being ready.  For example, a
  3107. select_read() event handler should try to read as much data from a
  3108. filehandle as it can.  The filehandle will stop being ready for
  3109. reading only when all its data has been read out.
  3110.  
  3111. Select events include two parameters.
  3112.  
  3113. C<ARG0> holds the handle of the file that is ready.
  3114.  
  3115. C<ARG1> contains 0, 1, or 2 to indicate whether the filehandle is
  3116. ready for reading, writing, or out-of-band reading (otherwise knows as
  3117. "expedited" or "exception").
  3118.  
  3119. C<ARG0> and the other event handler parameter constants is covered in
  3120. L<POE::Session>.
  3121.  
  3122. Sessions will not spontaneously stop as long as they are watching at
  3123. least one filehandle.
  3124.  
  3125. =over 2
  3126.  
  3127. =item select_read FILE_HANDLE, EVENT_NAME
  3128.  
  3129. =item select_read FILE_HANDLE
  3130.  
  3131. select_read() starts or stops the kernel from watching to see if a
  3132. filehandle can be read from.  An EVENT_NAME event will be enqueued
  3133. whenever the filehandle has data to be read.
  3134.  
  3135.   # Emit 'do_a_read' event whenever $filehandle has data to be read.
  3136.   $kernel->select_read( $filehandle, 'do_a_read' );
  3137.  
  3138.   # Stop watching for data to be read from $filehandle.
  3139.   $kernel->select_read( $filehandle );
  3140.  
  3141. select_read() does not return a meaningful value.
  3142.  
  3143. =item select_write FILE_HANDLE, EVENT_NAME
  3144.  
  3145. =item select_write FILE_HANDLE
  3146.  
  3147. select_write() starts or stops the kernel from watching to see if a
  3148. filehandle can be written to.  An EVENT_NAME event will be enqueued
  3149. whenever it is possible to write data to the filehandle.
  3150.  
  3151.   # Emit 'flush_data' whenever $filehandle can be written to.
  3152.   $kernel->select_writ( $filehandle, 'flush_data' );
  3153.  
  3154.   # Stop watching for opportunities to write to $filehandle.
  3155.   $kernel->select_write( $filehandle );
  3156.  
  3157. select_write() does not return a meaningful value.
  3158.  
  3159. =item select_expedite FILE_HANDLE, EVENT_NAME
  3160.  
  3161. =item select_expedite FILE_HANDLE
  3162.  
  3163. select_expedite() starts or stops the kernel from watching to see if a
  3164. filehandle can be read from "out-of-band".  This is most useful for
  3165. datagram sockets where an out-of-band condition is meaningful.  In
  3166. most cases it can be ignored.  An EVENT_NAME event will be enqueued
  3167. whetever the filehandle can be read from out-of-band.
  3168.  
  3169. Out of band data is called "expedited" because it's often available
  3170. ahead of a file or socket's normal data.  It's also used in socket
  3171. operations such as connect() to signal an exception.
  3172.  
  3173.   # Emit 'do_an_oob_read' whenever $filehandle has OOB data to be read.
  3174.   $kernel->select_expedite( $filehandle, 'do_an_oob_read' );
  3175.  
  3176.   # Stop watching for OOB data on the $filehandle.
  3177.   $kernel->select_expedite( $filehandle );
  3178.  
  3179. select_expedite() does not return a meaningful value.
  3180.  
  3181. =item select_pause_write FILE_HANDLE
  3182.  
  3183. =item select_resume_write FILE_HANDLE
  3184.  
  3185. select_pause_write() temporarily pauses event generation when a
  3186. FILE_HANDLE can be written to.  select_resume_write() turns event
  3187. generation back on.
  3188.  
  3189. These functions are more efficient than select_write() because they
  3190. don't perform full resource management.
  3191.  
  3192. Pause and resume a filehandle's writable events:
  3193.  
  3194.   $kernel->select_pause_write( $filehandle );
  3195.   $kernel->select_resume_write( $filehandle );
  3196.  
  3197. These methods don't return meaningful values.
  3198.  
  3199. =item select FILE_HANDLE, READ_EVENT_NM, WRITE_EVENT_NM, EXPEDITE_EVENT_NM
  3200.  
  3201. POE::Kernel's select() method alters a filehandle's read, write, and
  3202. expedite selects at the same time.  It's one method call more
  3203. expensive than doing the same thing manually, but it's more convenient
  3204. to code.
  3205.  
  3206. Defined event names set or change the events that will be emitted when
  3207. the filehandle becomes ready.  Undefined names clear those aspects of
  3208. the watcher, stopping it from generating those types of events.
  3209.  
  3210. This sets all three types of events at once.
  3211.  
  3212.   $kernel->select( $filehandle, 'do_read', 'do_flush', 'do_read_oob' );
  3213.  
  3214. This clears all three types of events at once.  If this filehandle is
  3215. the only thing keeping a session alive, then clearing its selects will
  3216. stop the session.
  3217.  
  3218.   $kernel->select( $filehandle );
  3219.  
  3220. This sets up a filehandle for read-only operation.
  3221.  
  3222.   $kernel->select( $filehandle, 'do_read', undef, 'do_read_oob' );
  3223.  
  3224. This sets up a filehandle for write-only operation.
  3225.  
  3226.   $kernel->select( $filehandle, undef, 'do_flush' );
  3227.  
  3228. This method does not return a meaningful value.
  3229.  
  3230. =back
  3231.  
  3232. =head2 Signal Watcher Methods
  3233.  
  3234. First some general notes about signal events and handling them.
  3235.  
  3236. Signal events are dispatched to sessions that have registered interest
  3237. in them via the C<sig()> method.  For backward compatibility, every
  3238. other session will receive a _signal event after that.  The _signal
  3239. event is scheduled to be removed in version 0.22, so please use
  3240. C<sig()> to register signal handlers instead.  In the meantime,
  3241. _signal events contain the same parameters as ones generated by
  3242. C<sig()>.  L<POE::Session> covers signal events in more details.
  3243.  
  3244. Signal events propagate to child sessions before their parents.  This
  3245. ensures that leaves of the parent/child tree are signaled first.  By
  3246. the time a session receives a signal, all its descendents already
  3247. have.
  3248.  
  3249. The Kernel acts as the ancestor of every session.  Signalling it, as
  3250. the operating system does, propagates signal events to every session.
  3251.  
  3252. It is possible to post fictitious signals from within POE.  These are
  3253. injected into the queue as if they came from the operating system, but
  3254. they are not limited to signals that the system recognizes.  POE uses
  3255. fictitious signals to notify every session about certain global
  3256. events, such as when a user interface has been destroyed.
  3257.  
  3258. Sessions that do not handle signal events may incur side effects.  In
  3259. particular, some signals are "terminal", in that they terminate a
  3260. program if they are not handled.  Many of the signals that usually
  3261. stop a program in UNIX are terminal in POE.
  3262.  
  3263. POE also recognizes "non-maskable" signals.  These will terminate a
  3264. program even when they are handled.  The signal that indicates user
  3265. interface destruction is just such a non-maskable signal.
  3266.  
  3267. Event handlers use sig_handled() to tell POE when a signal has been
  3268. handled.  Some unhandled signals will terminate a program.  Handling
  3269. them is important if that is not desired.
  3270.  
  3271. Event handlers can also implicitly tell POE when a signal has been
  3272. handled, simply by returning some true value.  This is deprecated,
  3273. however, because it has been the source of constant trouble in the
  3274. past.  Please use sig_handled() in its place.
  3275.  
  3276. Handled signals will continue to propagate through the parent/child
  3277. hierarchy.
  3278.  
  3279. Signal handling in Perl is not safe by itself.  POE is written to
  3280. avoid as many signal problems as it can, but they still may occur.
  3281. SIGCHLD is a special exception: POE polls for child process exits
  3282. using waitpid() instead of a signal handler.  Spawning child processes
  3283. should be completely safe.
  3284.  
  3285. There are three signal levels.  They are listed from least to most
  3286. strident.
  3287.  
  3288. =over 2
  3289.  
  3290. =item benign
  3291.  
  3292. Benign signals just notify sessions that signals have been received.
  3293. They have no side effects if they are not handled.
  3294.  
  3295. =item terminal
  3296.  
  3297. Terminal signal may stop a program if they go unhandled.  If any event
  3298. handler calls C<sig_handled()>, however, then the program will
  3299. continue to live.
  3300.  
  3301. In the past, only sessions that handled signals would survive.  All
  3302. others would be terminated.  This led to inconsistent states when some
  3303. programs were signaled.
  3304.  
  3305. The terminal system signals are: HUP, INT, KILL, QUIT and TERM.  There
  3306. is also one terminal fictitious signal, IDLE, which is used to notify
  3307. leftover sessions when a program has run out of things to do.
  3308.  
  3309. =item nonmaskable
  3310.  
  3311. Nonmaskable signals are similar to terminal signals, but they stop a
  3312. program regardless whether it has been handled.  POE implements two
  3313. nonmaskable signals, both of which are fictitious.
  3314.  
  3315. ZOMBIE is fired if the terminal signal IDLE did not wake anything up.
  3316. It is used to stop the remaining "zombie" sessions so that an inactive
  3317. program will exit cleanly.
  3318.  
  3319. UIDESTROY is fired when a main or top-level user interface widget has
  3320. been destroyed.  It is used to shut down programs when their
  3321. interfaces have been closed.
  3322.  
  3323. =back
  3324.  
  3325. Some system signals are handled specially.  These are SIGCHLD/SIGCLD,
  3326. SIGPIPE, and SIGWINCH.
  3327.  
  3328. =over 2
  3329.  
  3330. =item SIGCHLD/SIGCLD Events
  3331.  
  3332. POE::Kernel generates the same event when it receives either a SIGCHLD
  3333. or SIGCLD signal from the operating system.  This alleviates the need
  3334. for sessions to check both signals.
  3335.  
  3336. Additionally, the Kernel will determine the ID and return value of the
  3337. exiting child process.  The values are broadcast to every session, so
  3338. several sessions can check whether a departing child process is
  3339. theirs.
  3340.  
  3341. The SIGCHLD/SIGCHLD signal event comes with three custom parameters.
  3342.  
  3343. C<ARG0> contains 'CHLD', even if SIGCLD was caught.  C<ARG1> contains
  3344. the ID of the exiting child process.  C<ARG2> contains the return
  3345. value from C<$?>.
  3346.  
  3347. =item SIGPIPE Events
  3348.  
  3349. Normally, system signals are posted to the Kernel so they can
  3350. propagate to every session.  SIGPIPE is an exception to this rule.  It
  3351. is posted to the session that is currently running.  It still will
  3352. propagate through that session's children, but it will not go beyond
  3353. that parent/child tree.
  3354.  
  3355. =item SIGWINCH Events
  3356.  
  3357. Window resizes can generate a large number of signals very quickly,
  3358. and this can easily cause perl to dump core.  Because of this, POE
  3359. usually ignores SIGWINCH outright.
  3360.  
  3361. Signal handling in Perl 5.8.0 will be safer, and POE will take
  3362. advantage of that to enable SIGWINCH again.
  3363.  
  3364. POE will also handle SIGWINCH if the Event module is used.
  3365.  
  3366. =back
  3367.  
  3368. Finally, here are POE::Kernel's signal methods themselves.
  3369.  
  3370. =over 2
  3371.  
  3372. =item sig SIGNAL_NAME, EVENT_NAME
  3373.  
  3374. =item sig SIGNAL_NAME
  3375.  
  3376. sig() registers or unregisters a EVENT_NAME event for a particular
  3377. SIGNAL_NAME.  Signal names are the same as %SIG uses, with one
  3378. exception: CLD is always delivered as CHLD, so handling CHLD will
  3379. always do the right thing.
  3380.  
  3381.   $kernel->sig( INT => 'event_sigint' );
  3382.  
  3383. To unregister a signal handler, just leave off the event it should
  3384. generate, or pass it in undefined.
  3385.  
  3386.   $kernel->sig( 'INT' );
  3387.   $kernel->sig( INT => undef );
  3388.  
  3389. It's possible to register events for signals that the operating system
  3390. will never generate.  These "fictitious" signals can however be
  3391. generated through POE's signal() method instead of kill(2).
  3392.  
  3393. The sig() method does not return a meaningful value.
  3394.  
  3395. =item sig_handled
  3396.  
  3397. sig_handled() informs POE that a signal was handled.  It is only
  3398. meaningful within event handlers that are triggered by signals.
  3399.  
  3400. =item signal SESSION, SIGNAL_NAME, OPTIONAL_ARGS
  3401.  
  3402. =item signal SESSION, SIGNAL_NAME
  3403.  
  3404. signal() posts a signal event to a particular session (and its
  3405. children) through POE::Kernel rather than actually signalling the
  3406. process through the operating system.  Because it injects signal
  3407. events directly into POE's Kernel, its SIGNAL_NAME doesn't have to be
  3408. one the operating system understands.
  3409.  
  3410. For example, this posts a fictitious signal to some session:
  3411.  
  3412.   $kernel->signal( $session, 'DIEDIEDIE' );
  3413.  
  3414. POE::Kernel's signal() method doesn't return a meaningful value.
  3415.  
  3416. =item signal_ui_destroy WIDGET
  3417.  
  3418. This registers a widget with POE::Kernel such that the Kernel fires a
  3419. UIDESTROY signal when the widget is closed or destroyed.  The exact
  3420. trigger depends on the graphical toolkit currently being used.
  3421.  
  3422.   # Fire a UIDESTROY signal when this top-level window is deleted.
  3423.   $heap->{gtk_toplevel_window} = Gtk::Window->new('toplevel');
  3424.   $kernel->signal_ui_destroy( $heap->{gtk_toplevel_window} );
  3425.  
  3426. =back
  3427.  
  3428. =head2 Session Management Methods
  3429.  
  3430. These methods manage sessions.
  3431.  
  3432. =over 2
  3433.  
  3434. =item detach_child SESSION
  3435.  
  3436. Detaches SESSION from the current session.  SESSION must be a child of
  3437. the current session, or this call will fail.  detach_child() returns 1
  3438. on success.  If it fails, it returns false and sets $! to one of the
  3439. following values:
  3440.  
  3441. ESRCH indicates that SESSION is not a valid session.
  3442.  
  3443. EPERM indicates that SESSION is not a child of the current session.
  3444.  
  3445. This call may generate corresponding _parent and/or _child events.
  3446. See PREDEFINED EVENT NAMES in POE::Session's manpage for more
  3447. information about _parent and _child events.
  3448.  
  3449. =item detach_myself
  3450.  
  3451. Detaches the current session from it parent.  The parent session stops
  3452. owning the current one.  The current session is instead made a child
  3453. of POE::Kernel.  detach_child() returns 1 on success.  If it fails, it
  3454. returns 0 and sets $! to EPERM to indicate that the currest session
  3455. already is a child of POE::Kernel and cannot be detached from it.
  3456.  
  3457. This call may generate corresponding _parent and/or _child events.
  3458. See PREDEFINED EVENT NAMES in POE::Session's manpage for more
  3459. information about _parent and _child events.
  3460.  
  3461. =back
  3462.  
  3463. =head2 State Management Methods
  3464.  
  3465. State management methods let sessions hot swap their event handlers.
  3466. It would be rude to change another session's handlers, so these
  3467. methods only affect the current one.
  3468.  
  3469. =over 2
  3470.  
  3471. =item state EVENT_NAME
  3472.  
  3473. =item state EVENT_NAME, CODE_REFERENCE
  3474.  
  3475. =item state EVENT_NAME, OBJECT_REFERENCE
  3476.  
  3477. =item state EVENT_NAME, OBJECT_REFERENCE, OBJECT_METHOD_NAME
  3478.  
  3479. =item state EVENT_NAME, PACKAGE_NAME
  3480.  
  3481. =item state EVENT_NAME, PACKAGE_NAME, PACKAGE_METHOD_NAME
  3482.  
  3483. Depending on how it's used, state() can add, remove, or update an
  3484. event handler in the current session.
  3485.  
  3486. The simplest form of state() call deletes a handler for an event.
  3487. This example removes the current session's "do_this" handler.
  3488.  
  3489.   $kernel->state( 'do_this' );
  3490.  
  3491. The next form assigns a coderef to an event.  If the event is already
  3492. being handled, its old handler will be discarded.  Any events already
  3493. in POE's queue will be dispatched to the new handler.
  3494.  
  3495. Plain coderef handlers are also called "inline" handlers because they
  3496. originally were defined with inline anonymous subs.
  3497.  
  3498.   $kernel->state( 'do_this', \&this_does_it );
  3499.  
  3500. The third and fourth forms register or replace a handler with an
  3501. object method.  These handlers are called "object states" or object
  3502. handlers.  The third form maps an event to a method with the same
  3503. name.
  3504.  
  3505.   $kernel->state( 'do_this', $with_this_object );
  3506.  
  3507. The fourth form maps an event to a method with a different name.
  3508.  
  3509.   $kernel->state( 'do_this', $with_this_object, $calling_this_method );
  3510.  
  3511. The fifth and sixth forms register or replace a handler with a package
  3512. method.  These handlers are called "package states" or package
  3513. handlers.  The fifth form maps an event to a function with the same
  3514. name.
  3515.  
  3516.   $kernel->state( 'do_this', $with_this_package );
  3517.  
  3518. The sixth form maps an event to a function with a different name.
  3519.  
  3520.   $kernel->state( 'do_this', $with_this_package, $calling_this_function );
  3521.  
  3522. POE::Kernel's state() method returns 0 on success or a nonzero code
  3523. explaining why it failed:
  3524.  
  3525. ESRCH: The Kernel doesn't recognize the currently active session.
  3526. This happens when state() is called when no session is active.
  3527.  
  3528. =back
  3529.  
  3530. =head2 External Reference Count Methods
  3531.  
  3532. The Kernel internally maintains reference counts on sessions that have
  3533. active resource watchers.  The reference counts are used to ensure
  3534. that a session doesn't self-destruct while it's doing something
  3535. important.
  3536.  
  3537. POE::Kernel's external reference counting methods let resource watcher
  3538. developers manage their own reference counts.  This lets the watchers
  3539. keep their sessions alive when necessary.
  3540.  
  3541. =over 2
  3542.  
  3543. =item refcount_increment SESSION_ID, REFCOUNT_NAME
  3544.  
  3545. =item refcount_decrement SESSION_ID, REFCOUNT_NAME
  3546.  
  3547. refcount_increment() increments a session's external reference count,
  3548. returning the reference count after the increment.
  3549.  
  3550. refcount_decrement() decrements a session's external reference count,
  3551. returning the reference count after the decrement.
  3552.  
  3553.   $new_count = $kernel->refcount_increment( $session_id, 'thingy' );
  3554.   $new_count = $kernel->refcount_decrement( $session_id, 'thingy' );
  3555.  
  3556. Both methods return undef on failure and set $! to explain the
  3557. failure.
  3558.  
  3559. ESRCH: There is no session SESSION_ID currently active.
  3560.  
  3561. =back
  3562.  
  3563. =head2 Kernel Data Accessors
  3564.  
  3565. The Kernel keeps some information which can be useful to other
  3566. libraries.  These functions provide a consistent, safe interface to
  3567. the Kernel's internal data.
  3568.  
  3569. =over 2
  3570.  
  3571. =item get_active_session
  3572.  
  3573. get_active_session() returns a reference to the session which is
  3574. currently running.  It returns a reference to the Kernel itself if no
  3575. other session is running.  This is one of the times where the Kernel
  3576. pretends it's just another session.
  3577.  
  3578.   my $active_session = $poe_kernel->get_active_session();
  3579.  
  3580. This is a convenient way for procedurally called libraries to get a
  3581. reference to the current session.  Otherwise a programmer would
  3582. tediously need to include C<SESSION> with every call.
  3583.  
  3584. =back
  3585.  
  3586. =head1 Using POE with Other Event Loops
  3587.  
  3588. POE::Kernel supports four event loops.  Three of them come from other
  3589. modules, and the Kernel will adapt to whichever one is loaded before
  3590. it.  The Kernel's resource functions are designed to work the same
  3591. regardless of the underlying event loop.
  3592.  
  3593. =over 2
  3594.  
  3595. =item POE's select() Loop
  3596.  
  3597. This is the default event loop.  It is included in POE::Kernel and
  3598. written in plain Perl for maximum portability.
  3599.  
  3600.   use POE;
  3601.  
  3602. =item Event's Loop
  3603.  
  3604. Event is written in C for maximum performance.  It requires either a C
  3605. compiler or a binary distribtution for your platform, and its C nature
  3606. allows it to implement safe signals.
  3607.  
  3608.   use Event;
  3609.   use POE;
  3610.  
  3611. =item Gtk's Event Loop
  3612.  
  3613. This loop allows POE to work in graphical programs using the Gtk-Perl
  3614. library.
  3615.  
  3616.   use Gtk;
  3617.   use POE;
  3618.  
  3619. =item IO::Poll
  3620.  
  3621. IO::Poll is potentially more efficient than POE's default select()
  3622. code in large scale clients and servers.
  3623.  
  3624.   use IO::Poll;
  3625.   use POE;
  3626.  
  3627. =item Tk's Event Loop
  3628.  
  3629. This loop allows POE to work in graphical programs using the Tk-Perl
  3630. library.  When using Tk with POE, POE supplies an already-created
  3631. $poe_main_window variable to use for your main window.  Calling Tk's
  3632. MainWindow->new() often has an undesired outcome.
  3633.  
  3634.   use Tk;
  3635.   use POE;
  3636.  
  3637. =back
  3638.  
  3639. External event loops expect plain coderefs as callbacks.  POE::Session
  3640. has a postback() method which will create callbacks these loops can
  3641. use.  Callbacks created with C<postback()> are designed to post POE
  3642. events when called, letting just about any loop's native callbacks
  3643. work with POE.  This includes widget callbacks and event watchers POE
  3644. never dreamt of.
  3645.  
  3646. =head2 Kernel's Debugging Features
  3647.  
  3648. POE::Kernel contains a number of assertion and tracing flags.  They
  3649. were originally created to debug POE::Kernel itself, but they are also
  3650. useful for tracking down other problems.
  3651.  
  3652. Assertions are the quiet ones.  They only create output when something
  3653. catastrophic has happened.  That output is almost always fatal.  They
  3654. are mainly used to check the sanity of POE's internal data structures.
  3655.  
  3656. Traces are assertions' annoying cousins.  They noisily report on the
  3657. status of a running POE::Kernel instance, but they are never fatal.
  3658.  
  3659. Assertions and traces incur performance penalties when enabled.  It's
  3660. probably a bad idea to enable them in live systems.  They are all
  3661. disabled by default.
  3662.  
  3663. Assertion and tracing flags can be defined before POE::Kernel is first
  3664. used.
  3665.  
  3666.   # Turn on everything.
  3667.   sub POE::Kernel::ASSERT_DEFAULT () { 1 }
  3668.   sub POE::Kernel::TRACE_DEFAULT  () { 1 }
  3669.   use POE;  # Includes POE::Kernel
  3670.  
  3671. It is also possible to enable them using shell environment variables.
  3672. The environment variables follow the same names as the constants in
  3673. this section, but "POE_" is prepended to them.
  3674.  
  3675.   POE_ASSERT_DEFAULT=1 POE_TRACE_DEFAULT=1 ./my_poe_program
  3676.  
  3677. Assertions will be discussed first.
  3678.  
  3679. =over 2
  3680.  
  3681. =item ASSERT_DATA
  3682.  
  3683. ASSERT_DATA enables a variety of runtime integrity checks within
  3684. POE::Kernel and its event loop bridges.  This can impose a significant
  3685. runtime penalty, so it is off by default.  The test programs for POE
  3686. all enable ASSERT_DEFAULT, which includes ASSERT_DATA.
  3687.  
  3688. =item ASSERT_DEFAULT
  3689.  
  3690. ASSERT_DEFAULT is used as the default value for all the other assert
  3691. constants.  Setting it true is a quick and reliable way to ensure all
  3692. assertions are enabled.
  3693.  
  3694. =item ASSERT_EVENTS
  3695.  
  3696. ASSERT_EVENTS enables checks for dispatching events to nonexistent
  3697. sessions.
  3698.  
  3699. =item ASSERT_FILES
  3700.  
  3701. ASSERT_FILES enables some runtime checks on the file multiplexing
  3702. syscalls used to drive POE.
  3703.  
  3704. =item ASSERT_RETVALS
  3705.  
  3706. ASSERT_RETVALS causes POE::Kernel to die if a method would return an
  3707. error.  See also TRACE_RETVALS if you want a runtime warning rather
  3708. than a hard error.
  3709.  
  3710. =item ASSERT_USAGE
  3711.  
  3712. ASSERT_USAGE enables runtime parameter checking in a lot of
  3713. POE::Kernel method calls.  These are disabled by default because they
  3714. impart a hefty performance penalty.
  3715.  
  3716. =back
  3717.  
  3718. Then there are the trace options.
  3719.  
  3720. =over 2
  3721.  
  3722. =item TRACE_DEFAULT
  3723.  
  3724. TRACE_DEFAULT is used as the default value for all the other trace
  3725. constants.  Setting it true is a quick and reliable way to ensure all
  3726. traces are enabled.
  3727.  
  3728. =item TRACE_DESTROY
  3729.  
  3730. Enable TRACE_DESTROY to receive a dump of the contents of Session
  3731. heaps when they finally DESTROY.  It is indispensible for finding
  3732. memory leaks, which often hide in Session heaps.
  3733.  
  3734. =item TRACE_EVENTS
  3735.  
  3736. The music goes around and around, and it comes out here.  TRACE_EVENTS
  3737. enables messages that tell what happens to FIFO and alarm events: when
  3738. they're queued, dispatched, or discarded, and what their handlers
  3739. return.
  3740.  
  3741. =item TRACE_FILENAME
  3742.  
  3743. By default, trace messages go to STDERR.  If you'd like them to go
  3744. elsewhere, set TRACE_FILENAME to the file where they should go.
  3745.  
  3746. =item TRACE_FILES
  3747.  
  3748. TRACE_FILES enables or disables messages that tell how files are being
  3749. processed within POE::Kernel and the event loop bridges.
  3750.  
  3751. =item TRACE_STATISTICS
  3752.  
  3753. B<This feature is experimental.  No doubt it will change.>
  3754.  
  3755. TRACE_STATISTICS enables runtime gathering and reporting of various
  3756. performance metrics within a POE program.  Some statistics include how
  3757. much time is spent processing event callbacks, time spent in POE's
  3758. dispatcher, and the time spent waiting for an event.  A report is
  3759. displayed just before run() returns, and the data can be retrieved at
  3760. any time using stat_getdata().
  3761.  
  3762. stat_getdata() returns a hashref of various statistics and their
  3763. values.  The statistics are calculated using a sliding window and vary
  3764. over time as a program runs.
  3765.  
  3766. =item TRACE_PROFILE
  3767.  
  3768. TRACE_PROFILE switches on event profiling.  This causes the Kernel to
  3769. keep a count of every event it dispatches.  A report of the events and
  3770. their frequencies is displayed just before run() returns, or at
  3771. any time via stat_show_profile().
  3772.  
  3773. =item TRACE_REFCNT
  3774.  
  3775. TRACE_REFCNT displays messages about reference counts for sessions,
  3776. including garbage collection tests (formerly TRACE_GARBAGE).  This is
  3777. perhaps the most useful debugging trace since it will explain why
  3778. sessions do or don't die.
  3779.  
  3780. =item TRACE_RETVALS
  3781.  
  3782. TRACE_RETVALS enables carping whenever a Kernel method is about to
  3783. return an error.  See ASSERT_RETVALS if you would like the Kernel to
  3784. be stricter than this.
  3785.  
  3786. =item TRACE_SESSIONS
  3787.  
  3788. TRACE_SESSIONS enables messages pertaining to session management.
  3789. These messages include notice when sessions are created or destroyed.
  3790. They also include parent and child relationship changes.
  3791.  
  3792. =item TRACE_SIGNALS
  3793.  
  3794. TRACE_SIGNALS enables or disables information about signals caught and
  3795. dispatched within POE::Kernel.
  3796.  
  3797. =back
  3798.  
  3799. =head1 POE::Kernel Exports
  3800.  
  3801. POE::Kernel exports two symbols for your coding enjoyment:
  3802. C<$poe_kernel> and C<$poe_main_window>.  POE::Kernel is implicitly
  3803. used by POE itself, so using POE gets you POE::Kernel (and its
  3804. exports) for free.
  3805.  
  3806. =over 2
  3807.  
  3808. =item $poe_kernel
  3809.  
  3810. $poe_kernel contains a reference to the process' POE::Kernel instance.
  3811. It's mainly useful for getting at the kernel from places other than
  3812. event handlers.
  3813.  
  3814. For example, programs can't call the Kernel's run() method without a
  3815. reference, and they normally don't get references to the Kernel
  3816. without being in a running event handler.  This gets them going:
  3817.  
  3818.   $poe_kernel->run();
  3819.  
  3820. It's also handy from within libraries, but event handlers themselves
  3821. receive C<KERNEL> parameters and don't need to use $poe_kernel
  3822. directly.
  3823.  
  3824. =item $poe_main_window
  3825.  
  3826. Some graphical toolkits (currently only Tk) require at least one
  3827. widget be created before their event loops are usable.  POE::Kernel
  3828. allocates a main window in these cases, and exports a reference to
  3829. that window in C<$poe_main_window>.  For all other toolkits, this
  3830. exported variable is undefined.
  3831.  
  3832. Programs are free to use C<$poe_main_window> for whatever needs.  They
  3833. may even assign a widget to it when using toolkits that don't require
  3834. an initial widget (Gtk for now).
  3835.  
  3836. $poe_main_window is undefined if a graphical toolkit isn't used.
  3837.  
  3838. See: signal_ui_destroy
  3839.  
  3840. =back
  3841.  
  3842. =head1 SEE ALSO
  3843.  
  3844. The SEE ALSO section in L<POE> contains a table of contents covering
  3845. the entire POE distribution.
  3846.  
  3847. =head1 BUGS
  3848.  
  3849. There is no mechanism in place to prevent external reference count
  3850. names from clashing.
  3851.  
  3852. Probably lots more.
  3853.  
  3854. =head1 AUTHORS & COPYRIGHTS
  3855.  
  3856. Please see L<POE> for more information about authors and contributors.
  3857.  
  3858. =cut
  3859.