1POE::Kernel(3)        User Contributed Perl Documentation       POE::Kernel(3)
2
3
4

NAME

6       POE::Kernel - an event-based application kernel in Perl
7

SYNOPSIS

9         use POE; # auto-includes POE::Kernel and POE::Session
10
11         POE::Session->create(
12           inline_states => {
13             _start => sub { $_[KERNEL]->yield("next") },
14             next   => sub {
15               print "tick...\n";
16               $_[KERNEL]->delay(next => 1);
17             },
18           },
19         );
20
21         POE::Kernel->run();
22         exit;
23
24       In the spirit of Perl, there are a lot of other ways to use POE.
25

DESCRIPTION

27       POE::Kernel is the heart of POE.  It provides the lowest-level
28       features: non-blocking multiplexed I/O, timers, and signal watchers are
29       the most significant.  Everything else is built upon this foundation.
30
31       POE::Kernel is not an event loop in itself.  For that it uses one of
32       several available POE::Loop interface modules.  See CPAN for modules in
33       the POE::Loop namespace.
34
35       POE's documentation assumes the reader understands the @_ offset
36       constants (KERNEL, HEAP, ARG0, etc.).  The curious or confused reader
37       will find more detailed explanation in POE::Session.
38

USING POE

40   Literally Using POE
41       POE.pm is little more than a class loader.  It implements some magic to
42       cut down on the setup work.
43
44       Parameters to "use POE" are not treated as normal imports.  Rather,
45       they're abbreviated modules to be included along with POE.
46
47         use POE qw(Component::Client::TCP).
48
49       As you can see, the leading "POE::" can be omitted this way.
50
51       POE.pm also includes POE::Kernel and POE::Session by default.  These
52       two modules are used by nearly all POE-based programs.  So the above
53       example is actually the equivalent of:
54
55         use POE;
56         use POE::Kernel;
57         use POE::Session;
58         use POE::Component::Client::TCP;
59
60   Using POE::Kernel
61       POE::Kernel needs to know which event loop you want to use.  This is
62       supported in three different ways:
63
64       The first way is to use an event loop module before using POE::Kernel
65       (or POE, which loads POE::Kernel for you):
66
67         use Tk; # or one of several others
68         use POE::Kernel.
69
70       POE::Kernel scans the list of modules already loaded, and it loads an
71       appropriate POE::Loop adapter if it finds a known event loop.
72
73       The next way is to explicitly load the POE::Loop class you want:
74
75         use POE qw(Loop::Gtk);
76
77       Finally POE::Kernel's "import()" supports more programmer-friendly
78       configuration:
79
80         use POE::Kernel { loop => "Gtk" };
81         use POE::Session;
82
83   Anatomy of a POE-Based Application
84       Programs using POE work like any other.  They load required modules,
85       perform some setup, run some code, and eventually exit.  Halting
86       Problem notwithstanding.
87
88       A POE-based application loads some modules, sets up one or more
89       sessions, runs the code in those sessions, and eventually exits.
90
91         use POE;
92         POE::Session->create( ... map events to code here ... );
93         POE::Kernel->run();
94         exit;
95
96   POE::Kernel singleton
97       The POE::Kernel is a singleton object; there can be only one
98       POE::Kernel instance within a process.  This allows many object methods
99       to also be package methods.
100
101   Sessions
102       POE implements isolated compartments called sessions.  Sessions play
103       the role of tasks or threads within POE.  POE::Kernel acts as POE's
104       task scheduler, doling out timeslices to each session by invoking
105       callbacks within them.
106
107       Callbacks are not preemptive.  As long as one is running, no others
108       will be dispatched.  This is known as cooperative multitasking.  Each
109       session must cooperate by returning to the central dispatching kernel.
110
111       Cooperative multitasking vastly simplifies data sharing, since no two
112       pieces of code may alter data at once.
113
114       A session may also take exclusive control of a program's time, if
115       necessary, by simply not returning in a timely fashion.  It's even
116       possible to write completely blocking programs that use POE as a state
117       machine rather than a cooperative dispatcher.
118
119       Every POE-based application needs at least one session.  Code cannot
120       run within POE without being a part of some session.  Likewise, a
121       threaded program always has a "thread zero".
122
123       Sessions in POE::Kernel should not be confused with POE::Session even
124       though the two are inextricably associated.  POE::Session adapts
125       POE::Kernel's dispatcher to a particular calling convention.  Other
126       POE::Session classes exist on the CPAN.  Some radically alter the way
127       event handlers are called.
128       <http://search.cpan.org/search?query=poe+session>.
129
130   Resources
131       Resources are events and things which may create new events, such as
132       timers, I/O watchers, and even other sessions.
133
134       POE::Kernel tracks resources on behalf of its active sessions.  It
135       generates events corresponding to these resources' activity, notifying
136       sessions when it's time to do things.
137
138       The conversation goes something like this:
139
140         Session: Be a dear, Kernel, and let me know when someone clicks on
141                  this widget.  Thanks so much!
142
143         [TIME PASSES]  [SFX: MOUSE CLICK]
144
145         Kernel: Right, then.  Someone's clicked on your widget.
146                 Here you go.
147
148       Furthermore, since the Kernel keeps track of everything sessions do, it
149       knows when a session has run out of tasks to perform.  When this
150       happens, the Kernel emits a "_stop" event at the dead session so it can
151       clean up and shutdown.
152
153         Kernel: Please switch off the lights and lock up; it's time to go.
154
155       Likewise, if a session stops on its own and there still are opened
156       resource watchers, the Kernel knows about them and cleans them up on
157       the session's behalf.  POE excels at long-running services because it
158       so meticulously tracks and cleans up resources.
159
160       POE::Resources and the POE::Resource classes implement each kind of
161       resource, which are summarized here and covered in greater detail
162       later.
163
164       Events.
165         An event is a message to a sessions.  Posting an event keeps both the
166         sender and the receiver alive until after the event has been
167         dispatched.  This is only guaranteed if both the sender and receiver
168         are in the same process.  Inter-Kernel message passing add-ons may
169         have other guarantees.  Please see their documentation for details.
170
171         The rationale is that the event is in play, so the receiver must
172         remain active for it to be dispatched.  The sender remains alive in
173         case the receiver would like to send back a response.
174
175         Posted events cannot be preemptively canceled.  They tend to be
176         short-lived in practice, so this generally isn't an issue.
177
178       Timers.
179         Timers allow an application to send a message to the future. Once
180         set, a timer will keep the destination session active until it goes
181         off and the resulting event is dispatched.
182
183       Aliases.
184         Session aliases are an application-controlled way of addressing a
185         session.  Aliases act as passive event watchers.  As long as a
186         session has an alias, some other session may send events to that
187         session by that name.  Aliases keep sessions alive as long as a
188         process has active sessions.
189
190         If the only sessions remaining are being kept alive solely by their
191         aliases, POE::Kernel will send them a terminal "IDLE" signal.  In
192         most cases this will terminate the remaining sessions and allow the
193         program to exit.  If the sessions remain in memory without waking up
194         on the "IDLE" signal, POE::Kernel sends them a non-maskable "ZOMBIE"
195         signal.  They are then forcibly removed, and the program will finally
196         exit.
197
198       I/O watchers.
199         A session will remain active as long as a session is paying attention
200         to some external data source or sink. See select_read and
201         select_write.
202
203       Child sessions.
204         A session acting as a parent of one or more other sessions will
205         remain active until all the child sessions stop.  This may be
206         bypassed by detaching the children from the parent.
207
208       Child processes.
209         Child process are watched by sig_child().  The sig_child() watcher
210         will keep the watching session active until the child process has
211         been reaped by POE::Kernel and the resulting event has been
212         dispatched.
213
214         All other signal watchers, including using "sig" to watch for "CHLD",
215         do not keep their sessions active.  If you need a session to remain
216         active when it's only watching for signals, have it set an alias or
217         one of its own public reference counters.
218
219       Public reference counters.
220         A session will remain active as long as it has one or more nonzero
221         public (or external) reference counter.
222
223   Session Lifespans
224       "Session" as a term is somewhat overloaded.  There are two related
225       concepts that share the name.  First there is the class POE::Session,
226       and objects created with it or related classes.  Second there is a data
227       structure within POE::Kernel that tracks the POE::Session objects in
228       play and the various resources owned by each.
229
230       The way POE's garbage collector works is that a session object gives
231       itself to POE::Kernel at creation time.  The Kernel then holds onto
232       that object as long as resources exist that require the session to
233       remain alive.  When all of these resources are destroyed or released,
234       the session object has nothing left to trigger activity.  POE::Kernel
235       notifies the object it's through, and cleans up its internal session
236       context.  The session object is released, and self-destructs in the
237       normal Perlish fashion.
238
239       Sessions may be stopped even if they have active resources.  For
240       example, a session may fail to handle a terminal signal.  In this case,
241       POE::Kernel forces the session to stop, and all resources associated
242       with the session are preemptively released.
243
244   Events
245       An event is a message that is sent from one part of the POE application
246       to another.  An event consists of the event's name, optional event-
247       specific parameters and OOB information.  An event may be sent from the
248       kernel, from a wheel or from a session.
249
250       An application creates an event with "post", "yield", "call" or even
251       "signal".  POE::Kernel creates events in response external stimulus
252       (signals, select, etc).
253
254       Event Handlers
255
256       An event is handled by a function called an event handler, which is
257       some code that is designated to be called when a particular event is
258       dispatched.  See "Event Handler Management" and POE::Session.
259
260       The term state is often used in place of event handler, especially when
261       treating sessions as event driven state machines.
262
263       Handlers are always called in scalar context for asynchronous events
264       (i.e. via post()).  Synchronous events, invoked with call(), are
265       handled in the same context that call() was called.
266
267       Event handlers may not directly return references to objects in the
268       "POE" namespace.  POE::Kernel will stringify these references to
269       prevent timing issues with certain objects' destruction.  For example,
270       this error handler would cause errors because a deleted wheel would not
271       be destructed when one might think:
272
273         sub handle_error {
274           warn "Got an error";
275           delete $_[HEAP]{wheel};
276         }
277
278       The delete() call returns the deleted wheel member, which is then
279       returned implicitly by handle_error().
280
281   Using POE with Other Event Loops
282       POE::Kernel supports any number of event loops.  Two are included in
283       the base distribution.  Historically, POE included other loops but they
284       were moved into a separate distribution.  You can find them and other
285       loops on the CPAN.
286
287       POE's public interfaces remain the same regardless of the event loop
288       being used.  Since most graphical toolkits include some form of event
289       loop, back-end code should be portable to all of them.
290
291       POE's cooperation with other event loops lets POE be embedded into
292       other software.  The common underlying event loop drives both the
293       application and POE.  For example, by using POE::Loop::Glib, one can
294       embed POE into Vim, irssi, and so on.  Application scripts can then
295       take advantage of POE::Component::Client::HTTP (and everything else) to
296       do large-scale work without blocking the rest of the program.
297
298       Because this is Perl, there are multiple ways to load an alternate
299       event loop.  The simplest way is to load the event loop before loading
300       POE::Kernel.
301
302         use Gtk;
303         use POE;
304
305       Remember that POE loads POE::Kernel internally.
306
307       POE::Kernel examines the modules loaded before it and detects that Gtk
308       has been loaded.  If POE::Loop::Gtk is available, POE loads and hooks
309       it into POE::Kernel automatically.
310
311       It's less mysterious to load the appropriate POE::Loop class directly.
312       Their names follow the format "POE::Loop::$loop_module_name", where
313       $loop_module_name is the name of the event loop module after each "::"
314       has been substituted with an underscore. It can be abbreviated using
315       POE's loader magic.
316
317         use POE qw( Loop::Event_Lib );
318
319       POE also recognizes XS loops, they reside in the
320       "POE::XS::Loop::$loop_module_name" namespace.  Using them may give you
321       a performance improvement on your platform, as the eventloop are some
322       of the hottest code in the system.  As always, benchmark your
323       application against various loops to see which one is best for your
324       workload and platform.
325
326         use POE qw( XS::Loop::EPoll );
327
328       Please don't load the loop modules directly, because POE will not have
329       a chance to initialize it's internal structures yet. Code written like
330       this will throw errors on startup. It might look like a bug in POE, but
331       it's just the way POE is designed.
332
333         use POE::Loop::IO_Poll;
334         use POE;
335
336       POE::Kernel also supports configuration directives on its own "use"
337       line.  A loop explicitly specified this way will override the search
338       logic.
339
340         use POE::Kernel { loop => "Glib" };
341
342       Finally, one may specify the loop class by setting the POE::Loop or
343       POE::XS:Loop class name in the POE_EVENT_LOOP environment variable.
344       This mechanism was added for tests that need to specify the loop from a
345       distance.
346
347         BEGIN { $ENV{POE_EVENT_LOOP} = "POE::XS::Loop::Poll" }
348         use POE;
349
350       Of course this may also be set from your shell:
351
352         % export POE_EVENT_LOOP='POE::XS::Loop::Poll'
353         % make test
354
355       Many external event loops support their own callback mechanisms.
356       POE::Session's "postback()" and "callback()" methods return plain Perl
357       code references that will generate POE events when called.
358       Applications can pass these code references to event loops for use as
359       callbacks.
360
361       POE's distribution includes two event loop interfaces.  CPAN holds
362       several more:
363
364       POE::Loop::Select (bundled)
365
366       By default POE uses its select() based loop to drive its event system.
367       This is perhaps the least efficient loop, but it is also the most
368       portable.  POE optimizes for correctness above all.
369
370       POE::Loop::IO_Poll (bundled)
371
372       The IO::Poll event loop provides an alternative that theoretically
373       scales better than select().
374
375       POE::Loop::Event (separate distribution)
376
377       This event loop provides interoperability with other modules that use
378       Event.  It may also provide a performance boost because Event is
379       written in a compiled language.  Unfortunately, this makes Event less
380       portable than Perl's built-in select().
381
382       POE::Loop::Gtk (separate distribution)
383
384       This event loop allows programs to work under the Gtk graphical
385       toolkit.
386
387       POE::Loop::Tk (separate distribution)
388
389       This event loop allows programs to work under the Tk graphical toolkit.
390       Tk has some restrictions that require POE to behave oddly.
391
392       Tk's event loop will not run unless one or more widgets are created.
393       POE must therefore create such a widget before it can run. POE::Kernel
394       exports $poe_main_window so that the application developer may use the
395       widget (which is a MainWindow), since POE doesn't need it other than
396       for dispatching events.
397
398       Creating and using a different MainWindow often has an undesired
399       outcome.
400
401       POE::Loop::EV (separate distribution)
402
403       POE::Loop::EV allows POE-based programs to use the EV event library
404       with little or no change.
405
406       POE::Loop::Glib (separate distribution)
407
408       POE::Loop::Glib allows POE-based programs to use Glib with little or no
409       change.  It also supports embedding POE-based programs into
410       applications that already use Glib.  For example, we have heard that
411       POE has successfully embedded into vim, irssi and xchat via this loop.
412
413       POE::Loop::Kqueue (separate distribution)
414
415       POE::Loop::Kqueue allows POE-based programs to transparently use the
416       BSD kqueue event library on operating systems that support it.
417
418       POE::Loop::Prima (separate distribution)
419
420       POE::Loop::Prima allows POE-based programs to use Prima's event loop
421       with little or no change.  It allows POE libraries to be used within
422       Prima applications.
423
424       POE::Loop::Wx (separate distribution)
425
426       POE::Loop::Wx allows POE-based programs to use Wx's event loop with
427       little or no change.  It allows POE libraries to be used within Wx
428       applications, such as Padre.
429
430       POE::XS::Loop::EPoll (separate distribution)
431
432       POE::XS::Loop::EPoll allows POE components to transparently use the
433       EPoll event library on operating systems that support it.
434
435       POE::XS::Loop::Poll (separate distribution)
436
437       POE::XS::Loop::Poll is a higher-performance C-based libpoll event loop.
438       It replaces some of POE's hot Perl code with C for better performance.
439
440       Other Event Loops (separate distributions)
441
442       POE may be extended to handle other event loops.  Developers are
443       invited to work with us to support their favorite loops.
444

PUBLIC METHODS

446       POE::Kernel encapsulates a lot of features.  The documentation for each
447       set of features is grouped by purpose.
448
449   Kernel Management and Accessors
450       ID
451
452       ID() currently returns POE::Kernel's unique identifier.  Every Kernel
453       instance is assigned a globally unique ID at birth.  has_forked()
454       alters the ID so that each forked process has a unique one, too.
455
456         % perl -wl -MPOE -e 'print $poe_kernel->ID'
457         macbookpoe.local-4d5305de-0000e6b8-00000001
458
459       The content of these IDs may change from time to time.  Your code
460       should not depend upon the current format.
461
462       Deprecation Warning 2011-02-09
463
464       Your code should not depend upon ID() remaining unique.  The uniqueness
465       will be removed in a future release of POE.  If you require unique IDs,
466       please see one of the fine GUID and/or UUID modules on the CPAN:
467
468         http://search.cpan.org/search?query=GUID&mode=dist
469         http://search.cpan.org/search?query=UUID&mode=dist
470
471       POE doesn't require globally or universally unique kernel IDs.  The
472       creation and maintenance of these IDs adds overhead to POE::Kernel's
473       has_forked() method.  Other modules do it better, upon demand, without
474       incurring overhead for those who don't need them.
475
476       run
477
478       run() runs POE::Kernel's event dispatcher.  It will not return until
479       all sessions have ended.  run() is a class method so a POE::Kernel
480       reference is not needed to start a program's execution.
481
482         use POE;
483         POE::Session->create( ... ); # one or more
484         POE::Kernel->run();          # set them all running
485         exit;
486
487       POE implements the Reactor pattern at its core.  Events are dispatched
488       to functions and methods through callbacks.  The code behind run()
489       waits for and dispatches events.
490
491       run() will not return until every session has ended.  This includes
492       sessions that were created while run() was running.
493
494       POE::Kernel will print a strong message if a program creates sessions
495       but fails to call run().  Prior to this warning, we received tons of
496       bug reports along the lines of "my POE program isn't doing anything".
497       It turned out that people forgot to start an event dispatcher, so
498       events were never dispatched.
499
500       If the lack of a run() call is deliberate, perhaps because some other
501       event loop already has control, you can avoid the message by calling it
502       before creating a session.  run() at that point will initialize POE and
503       return immediately.  POE::Kernel will be satisfied that run() was
504       called, although POE will not have actually taken control of the event
505       loop.
506
507         use POE;
508         POE::Kernel->run(); # silence the warning
509         POE::Session->create( ... );
510         exit;
511
512       Note, however, that this varies from one event loop to another.  If a
513       particular POE::Loop implementation doesn't support it, that's probably
514       a bug.  Please file a bug report with the owner of the relevant
515       POE::Loop module.
516
517       run_one_timeslice
518
519       run_one_timeslice() dispatches any events that are due to be delivered.
520       These events include timers that are due, asynchronous messages that
521       need to be delivered, signals that require handling, and notifications
522       for files with pending I/O.  Do not rely too much on event ordering.
523       run_one_timeslice() is defined by the underlying event loop, and its
524       timing may vary.
525
526       run() is implemented similar to
527
528         run_one_timeslice() while $session_count > 0;
529
530       run_one_timeslice() can be used to keep running POE::Kernel's
531       dispatcher while emulating blocking behavior.  The pattern is
532       implemented with a flag that is set when some asynchronous event
533       occurs.  A loop calls run_one_timeslice() until that flag is set.  For
534       example:
535
536         my $done = 0;
537
538         sub handle_some_event {
539           $done = 1;
540         }
541
542         $kernel->run_one_timeslice() while not $done;
543
544       Do be careful.  The above example will spin if POE::Kernel is done but
545       $done is never set.  The loop will never be done, even though there's
546       nothing left that will set $done.
547
548       run_while SCALAR_REF
549
550       run_while() is an experimental version of run_one_timeslice() that will
551       only return when there are no more active sessions, or the value of the
552       referenced scalar becomes false.
553
554       Here's a version of the run_one_timeslice() example using run_while()
555       instead:
556
557         my $job_count = 3;
558
559         sub handle_some_event {
560           $job_count--;
561         }
562
563         $kernel->run_while(\$job_count);
564
565       has_forked
566
567           my $pid = fork();
568           die "Unable to fork" unless defined $pid;
569           unless( $pid ) {
570               $poe_kernel->has_forked;
571           }
572
573       Inform the kernel that it is now running in a new process.  This allows
574       the kernel to reset some internal data to adjust to the new situation.
575
576       has_forked() must be called in the child process if you wish to run the
577       same kernel.  However, if you want the child process to have new
578       kernel, you must call "stop" instead.
579
580       Note: POE's internals will detect if a fork occurred before "run()" and
581       will call "has_forked()" automatically. If you are unsure whether you
582       need to call it or not, please enable "ASSERT_USAGE" and POE will emit
583       a warning if it's necessary.
584
585       stop
586
587       stop() causes POE::Kernel->run() to return early.  It does this by
588       emptying the event queue, freeing all used resources, and stopping
589       every active session.  stop() is not meant to be used lightly.  Proceed
590       with caution.
591
592       Caveats:
593
594       The session that calls stop() will not be fully DESTROYed until it
595       returns.  Invoking an event handler in the session requires a reference
596       to that session, and weak references are prohibited in POE for backward
597       compatibility reasons, so it makes sense that the last session won't be
598       garbage collected right away.
599
600       Sessions are not notified about their destruction.  If anything relies
601       on _stop being delivered, it will break and/or leak memory.
602
603       stop() is still considered experimental.  It was added to improve
604       fork() support for POE::Wheel::Run.  If it proves unfixably
605       problematic, it will be removed without much notice.
606
607       stop() is advanced magic.  Programmers who think they need it are
608       invited to become familiar with its source.
609
610       See "Running POE::Kernel in the Child" in POE::Wheel::Run for an
611       example of how to use this facility.
612
613   Asynchronous Messages (FIFO Events)
614       Asynchronous messages are events that are dispatched in the order in
615       which they were enqueued (the first one in is the first one out,
616       otherwise known as first-in/first-out, or FIFO order).  These methods
617       enqueue new messages for delivery.  The act of enqueuing a message
618       keeps the sender alive at least until the message is delivered.
619
620       post DESTINATION, EVENT_NAME [, PARAMETER_LIST]
621
622       post() enqueues a message to be dispatched to a particular DESTINATION
623       session.  The message will be handled by the code associated with
624       EVENT_NAME.  If a PARAMETER_LIST is included, its values will also be
625       passed along.
626
627         POE::Session->create(
628           inline_states => {
629             _start => sub {
630               $_[KERNEL]->post( $_[SESSION], "event_name", 0 );
631             },
632             event_name => sub {
633               print "$_[ARG0]\n";
634               $_[KERNEL]->post( $_[SESSION], "event_name", $_[ARG0] + 1 );
635             },
636           }
637         );
638
639       post() returns a Boolean value indicating whether the message was
640       successfully enqueued.  If post() returns false, $! is set to explain
641       the failure:
642
643       ESRCH ("No such process") - The DESTINATION session did not exist at
644       the time post() was called.
645
646       yield EVENT_NAME [, PARAMETER_LIST]
647
648       yield() is a shortcut for post() where the destination session is the
649       same as the sender.  This example is equivalent to the one for post():
650
651         POE::Session->create(
652           inline_states => {
653             _start => sub {
654               $_[KERNEL]->yield( "event_name", 0 );
655             },
656             event_name => sub {
657               print "$_[ARG0]\n";
658               $_[KERNEL]->yield( "event_name", $_[ARG0] + 1 );
659             },
660           }
661         );
662
663       As with post(), yield() returns right away, and the enqueued EVENT_NAME
664       is dispatched later.  This may be confusing if you're already familiar
665       with threading.
666
667       yield() should always succeed, so it does not return a meaningful
668       value.
669
670   Synchronous Messages
671       It is sometimes necessary for code to be invoked right away.  For
672       example, some resources must be serviced right away, or they'll
673       faithfully continue reporting their readiness.  These reports would
674       appear as a stream of duplicate events.  Synchronous events can also
675       prevent data from going stale between the time an event is enqueued and
676       the time it's delivered.
677
678       Synchronous event handlers preempt POE's event queue, so they should
679       perform simple tasks of limited duration.  Synchronous events that need
680       to do more than just service a resource should pass the resource's
681       information to an asynchronous handler.  Otherwise synchronous
682       operations will occur out of order in relation to asynchronous events.
683       It's very easy to have race conditions or break causality this way, so
684       try to avoid it unless you're okay with the consequences.
685
686       POE provides these ways to call message handlers right away.
687
688       call DESTINATION, EVENT_NAME [, PARAMETER_LIST]
689
690       call()'s semantics are nearly identical to post()'s.  call() invokes a
691       DESTINATION's handler associated with an EVENT_NAME.  An optional
692       PARAMETER_LIST will be passed along to the message's handler.  The
693       difference, however, is that the handler will be invoked immediately,
694       even before call() returns.
695
696       call() returns the value returned by the EVENT_NAME handler.  It can do
697       this because the handler is invoked before call() returns.  call() can
698       therefore be used as an accessor, although there are better ways to
699       accomplish simple accessor behavior.
700
701         POE::Session->create(
702           inline_states => {
703             _start => sub {
704               print "Got: ", $_[KERNEL]->call($_[SESSION], "do_now"), "\n";
705             },
706             do_now => sub {
707               return "some value";
708             }
709           }
710         );
711
712       The POE::Wheel classes uses call() to synchronously deliver I/O
713       notifications.  This avoids a host of race conditions.
714
715       call() may fail in the same way and for the same reasons as post().  On
716       failure, $! is set to some nonzero value indicating why.  Since call()
717       may return undef as a matter of course, it's recommended that $! be
718       checked for the error condition as well as the explanation.
719
720       ESRCH ("No such process") - The DESTINATION session did not exist at
721       the time post() was called.
722
723   Timer Events (Delayed Messages)
724       It's often useful to wait for a certain time or until a certain amount
725       of time has passed.  POE supports this with events that are deferred
726       until either an absolute time ("alarms") or until a certain duration of
727       time has elapsed ("delays").
728
729       Timer interfaces are further divided into two groups.  One group
730       identifies timers by the names of their associated events.  Another
731       group identifies timers by a unique identifier returned by the timer
732       constructors.  Technically, the two are both name-based, but the
733       "identifier-based" timers provide a second, more specific handle to
734       identify individual timers.
735
736       Timers may only be set up for the current session.  This design was
737       modeled after alarm() and SIGALRM, which only affect the current UNIX
738       process.  Each session has a separate namespace for timer names.  Timer
739       methods called in one session cannot affect the timers in another.  As
740       you may have noticed, quite a lot of POE's API is designed to prevent
741       sessions from interfering with each other.
742
743       The best way to simulate deferred inter-session messages is to send an
744       immediate message that causes the destination to set a timer.  The
745       destination's timer then defers the action requested of it.  This way
746       is preferred because the time spent communicating the request between
747       sessions may not be trivial, especially if the sessions are separated
748       by a network.  The destination can determine how much time remains on
749       the requested timer and adjust its wait time accordingly.
750
751       Name-Based Timers
752
753       Name-based timers are identified by the event names used to set them.
754       It is possible for different sessions to use the same timer event
755       names, since each session is a separate compartment with its own timer
756       namespace.  It is possible for a session to have multiple timers for a
757       given event, but results may be surprising.  Be careful to use the
758       right timer methods.
759
760       The name-based timer methods are alarm(), alarm_add(), delay(), and
761       delay_add().
762
763       alarm EVENT_NAME [, EPOCH_TIME [, PARAMETER_LIST] ]
764
765       alarm() clears all existing timers in the current session with the same
766       EVENT_NAME.  It then sets a new timer, named EVENT_NAME, that will fire
767       EVENT_NAME at the current session when EPOCH_TIME has been reached.  An
768       optional PARAMETER_LIST may be passed along to the timer's handler.
769
770       Omitting the EPOCH_TIME and subsequent parameters causes alarm() to
771       clear the EVENT_NAME timers in the current session without setting a
772       new one.
773
774       EPOCH_TIME is the UNIX epoch time.  You know, seconds since midnight,
775       1970-01-01.  POE uses Time::HiRes::time(), which allows EPOCH_TIME to
776       be (or include) fractional seconds.
777
778       POE supports fractional seconds, but accuracy falls off steeply after
779       1/100 second.  Mileage will vary depending on your CPU speed and your
780       OS time resolution.
781
782       Be sure to use Time::HiRes::time() rather than Perl's built-in time()
783       if sub-second accuracy matters at all.  The built-in time() returns
784       floor(Time::HiRes::time()), which is nearly always some fraction of a
785       second in the past.  For example the high-resolution time might be
786       1200941422.89996.  At that same instant, time() would be 1200941422.
787       An alarm for time() + 0.5 would be 0.39996 seconds in the past, so it
788       would be dispatched immediately (if not sooner).
789
790       POE's event queue is time-ordered, so a timer due before time() will be
791       delivered ahead of other events but not before timers with even earlier
792       due times.  Therefore an alarm() with an EPOCH_TIME before time() jumps
793       ahead of the queue.
794
795       All timers are implemented identically internally, regardless of how
796       they are set.  alarm() will therefore blithely clear timers set by
797       other means.
798
799         POE::Session->create(
800           inline_states => {
801             _start => sub {
802               $_[KERNEL]->alarm( tick => time() + 1, 0 );
803             },
804             tick => sub {
805               print "tick $_[ARG0]\n";
806               $_[KERNEL]->alarm( tock => time() + 1, $_[ARG0] + 1 );
807             },
808             tock => sub {
809               print "tock $_[ARG0]\n";
810               $_[KERNEL]->alarm( tick => time() + 1, $_[ARG0] + 1 );
811             },
812           }
813         );
814
815       alarm() returns 0 on success or a true value on failure.  Usually
816       EINVAL to signal an invalid parameter, such as an undefined EVENT_NAME.
817
818       alarm_add EVENT_NAME, EPOCH_TIME [, PARAMETER_LIST]
819
820       alarm_add() is used to add a new alarm timer named EVENT_NAME without
821       clearing existing timers.  EPOCH_TIME is a required parameter.
822       Otherwise the semantics are identical to alarm().
823
824       A program may use alarm_add() without first using alarm().
825
826         POE::Session->create(
827           inline_states => {
828             _start => sub {
829               $_[KERNEL]->alarm_add( tick => time() + 1.0, 1_000_000 );
830               $_[KERNEL]->alarm_add( tick => time() + 1.5, 2_000_000 );
831             },
832             tick => sub {
833               print "tick $_[ARG0]\n";
834               $_[KERNEL]->alarm_add( tock => time() + 1, $_[ARG0] + 1 );
835             },
836             tock => sub {
837               print "tock $_[ARG0]\n";
838               $_[KERNEL]->alarm_add( tick => time() + 1, $_[ARG0] + 1 );
839             },
840           }
841         );
842
843       alarm_add() returns 0 on success or EINVAL if EVENT_NAME or EPOCH_TIME
844       is undefined.
845
846       delay EVENT_NAME [, DURATION_SECONDS [, PARAMETER_LIST] ]
847
848       delay() clears all existing timers in the current session with the same
849       EVENT_NAME.  It then sets a new timer, named EVENT_NAME, that will fire
850       EVENT_NAME at the current session when DURATION_SECONDS have elapsed
851       from "now".  An optional PARAMETER_LIST may be passed along to the
852       timer's handler.
853
854       Omitting the DURATION_SECONDS and subsequent parameters causes delay()
855       to clear the EVENT_NAME timers in the current session without setting a
856       new one.
857
858       DURATION_SECONDS may be or include fractional seconds.  As with all of
859       POE's timers, accuracy falls off steeply after 1/100 second.  Mileage
860       will vary depending on your CPU speed and your OS time resolution.
861
862       POE's event queue is time-ordered, so a timer due before time() will be
863       delivered ahead of other events but not before timers with even earlier
864       due times.  Therefore a delay () with a zero or negative
865       DURATION_SECONDS jumps ahead of the queue.
866
867       delay() may be considered a shorthand form of alarm(), but there are
868       subtle differences in timing issues.  This code is roughly equivalent
869       to the alarm() example.
870
871         POE::Session->create(
872           inline_states => {
873             _start => sub {
874               $_[KERNEL]->delay( tick => 1, 0 );
875             },
876             tick => sub {
877               print "tick $_[ARG0]\n";
878               $_[KERNEL]->delay( tock => 1, $_[ARG0] + 1 );
879             },
880             tock => sub {
881               print "tock $_[ARG0]\n";
882               $_[KERNEL]->delay( tick => 1, $_[ARG0] + 1 );
883             },
884           }
885         );
886
887       delay() returns 0 on success or a reason for failure: EINVAL if
888       EVENT_NAME is undefined.
889
890       delay_add EVENT_NAME, DURATION_SECONDS [, PARAMETER_LIST]
891
892       delay_add() is used to add a new delay timer named EVENT_NAME without
893       clearing existing timers.  DURATION_SECONDS is a required parameter.
894       Otherwise the semantics are identical to delay().
895
896       A program may use delay_add() without first using delay().
897
898         POE::Session->create(
899           inline_states => {
900             _start => sub {
901               $_[KERNEL]->delay_add( tick => 1.0, 1_000_000 );
902               $_[KERNEL]->delay_add( tick => 1.5, 2_000_000 );
903             },
904             tick => sub {
905               print "tick $_[ARG0]\n";
906               $_[KERNEL]->delay_add( tock => 1, $_[ARG0] + 1 );
907             },
908             tock => sub {
909               print "tock $_[ARG0]\n";
910               $_[KERNEL]->delay_add( tick => 1, $_[ARG0] + 1 );
911             },
912           }
913         );
914
915       delay_add() returns 0 on success or EINVAL if EVENT_NAME or EPOCH_TIME
916       is undefined.
917
918       Identifier-Based Timers
919
920       A second way to manage timers is through identifiers.  Setting an alarm
921       or delay with the "identifier" methods allows a program to manipulate
922       several timers with the same name in the same session.  As covered in
923       alarm() and delay() however, it's possible to mix named and identified
924       timer calls, but the consequences may not always be expected.
925
926       alarm_set EVENT_NAME, EPOCH_TIME [, PARAMETER_LIST]
927
928       alarm_set() sets an alarm, returning a unique identifier that can be
929       used to adjust or remove the alarm later.  Unlike alarm(), it does not
930       first clear existing timers with the same EVENT_NAME.  Otherwise the
931       semantics are identical to alarm().
932
933         POE::Session->create(
934           inline_states => {
935             _start => sub {
936               $_[HEAP]{alarm_id} = $_[KERNEL]->alarm_set(
937                 party => time() + 1999
938               );
939               $_[KERNEL]->delay(raid => 1);
940             },
941             raid => sub {
942               $_[KERNEL]->alarm_remove( delete $_[HEAP]{alarm_id} );
943             },
944           }
945         );
946
947       alarm_set() returns false if it fails and sets $! with the explanation.
948       $! will be EINVAL if EVENT_NAME or TIME is undefined.
949
950       alarm_adjust ALARM_ID, DELTA_SECONDS
951
952       alarm_adjust() adjusts an existing timer's due time by DELTA_SECONDS,
953       which may be positive or negative.  It may even be zero, but that's not
954       as useful.  On success, it returns the timer's new due time since the
955       start of the UNIX epoch.
956
957       It's possible to alarm_adjust() timers created by delay_set() as well
958       as alarm_set().
959
960       This example moves an alarm's due time ten seconds earlier.
961
962         use POSIX qw(strftime);
963
964         POE::Session->create(
965           inline_states => {
966             _start => sub {
967               $_[HEAP]{alarm_id} = $_[KERNEL]->alarm_set(
968                 party => time() + 1999
969               );
970               $_[KERNEL]->delay(postpone => 1);
971             },
972             postpone => sub {
973               my $new_time = $_[KERNEL]->alarm_adjust(
974                 $_[HEAP]{alarm_id}, -10
975               );
976               print(
977                 "Now we're gonna party like it's ",
978                 strftime("%F %T", gmtime($new_time)), "\n"
979               );
980             },
981           }
982         );
983
984       alarm_adjust() returns Boolean false if it fails, setting $! to the
985       reason why.  $! may be EINVAL if ALARM_ID or DELTA_SECONDS are
986       undefined.  It may be ESRCH if ALARM_ID no longer refers to a pending
987       timer.  $! may also contain EPERM if ALARM_ID is valid but belongs to a
988       different session.
989
990       alarm_remove ALARM_ID
991
992       alarm_remove() removes the alarm identified by ALARM_ID.  ALARM_ID
993       comes from a previous alarm_set() or delay_set() call.
994
995       Upon success, alarm_remove() returns something true based on its
996       context.  In a list context, it returns three things: The removed
997       alarm's event name, the UNIX time it was due to go off, and a reference
998       to the PARAMETER_LIST (if any) assigned to the timer when it was
999       created.  If necessary, the timer can be re-set with this information.
1000
1001         POE::Session->create(
1002           inline_states => {
1003             _start => sub {
1004               $_[HEAP]{alarm_id} = $_[KERNEL]->alarm_set(
1005                 party => time() + 1999
1006               );
1007               $_[KERNEL]->delay(raid => 1);
1008             },
1009             raid => sub {
1010               my ($name, $time, $param) = $_[KERNEL]->alarm_remove(
1011                 $_[HEAP]{alarm_id}
1012               );
1013               print(
1014                 "Removed alarm for event $name due at $time with @$param\n"
1015               );
1016
1017               # Or reset it, if you'd like.  Possibly after modification.
1018               $_[KERNEL]->alarm_set($name, $time, @$param);
1019             },
1020           }
1021         );
1022
1023       In a scalar context, it returns a reference to a list of the three
1024       things above.
1025
1026         # Remove and reset an alarm.
1027         my $alarm_info = $_[KERNEL]->alarm_remove( $alarm_id );
1028         my $new_id = $_[KERNEL]->alarm_set(
1029           $alarm_info[0], $alarm_info[1], @{$alarm_info[2]}
1030         );
1031
1032       Upon failure, however, alarm_remove() returns a Boolean false value and
1033       sets $! with the reason why the call failed:
1034
1035       EINVAL ("Invalid argument") indicates a problem with one or more
1036       parameters, usually an undefined ALARM_ID.
1037
1038       ESRCH ("No such process") indicates that ALARM_ID did not refer to a
1039       pending alarm.
1040
1041       EPERM ("Operation not permitted").  A session cannot remove an alarm it
1042       does not own.
1043
1044       alarm_remove_all
1045
1046       alarm_remove_all() removes all the pending timers for the current
1047       session, regardless of creation method or type.  This method takes no
1048       arguments.  It returns information about the alarms that were removed,
1049       either as a list of alarms or a list reference depending whether
1050       alarm_remove_all() is called in scalar or list context.
1051
1052       Each removed alarm's information is identical to the format explained
1053       in alarm_remove().
1054
1055         sub some_event_handler {
1056           my @removed_alarms = $_[KERNEL]->alarm_remove_all();
1057           foreach my $alarm (@removed_alarms) {
1058             my ($name, $time, $param) = @$alarm;
1059             ...;
1060           }
1061         }
1062
1063       delay_set EVENT_NAME, DURATION_SECONDS [, PARAMETER_LIST]
1064
1065       delay_set() sets a timer for DURATION_SECONDS in the future.  The timer
1066       will be dispatched to the code associated with EVENT_NAME in the
1067       current session.  An optional PARAMETER_LIST will be passed through to
1068       the handler.  It returns the same sort of things that alarm_set() does.
1069
1070         POE::Session->create(
1071           inline_states => {
1072             _start => sub {
1073               $_[KERNEL]->delay_set("later", 5, "hello", "world");
1074             },
1075             later => sub {
1076               print "@_[ARG0..#$_]\n";
1077             }
1078           }
1079         );
1080
1081       delay_adjust ALARM_ID, SECONDS_FROM_NOW
1082
1083       delay_adjust() changes a timer's due time to be SECONDS_FROM_NOW.  It's
1084       useful for refreshing watchdog- or timeout-style timers.  On success it
1085       returns the new absolute UNIX time the timer will be due.
1086
1087       It's possible for delay_adjust() to adjust timers created by
1088       alarm_set() as well as delay_set().
1089
1090         use POSIX qw(strftime);
1091
1092         POE::Session->create(
1093           inline_states => {
1094             # Setup.
1095             # ... omitted.
1096
1097             got_input => sub {
1098               my $new_time = $_[KERNEL]->delay_adjust(
1099                 $_[HEAP]{input_timeout}, 60
1100               );
1101               print(
1102                 "Refreshed the input timeout.  Next may occur at ",
1103                 strftime("%F %T", gmtime($new_time)), "\n"
1104               );
1105             },
1106           }
1107         );
1108
1109       On failure it returns Boolean false and sets $! to a reason for the
1110       failure.  See the explanation of $! for alarm_adjust().
1111
1112       delay_remove is not needed
1113
1114       There is no delay_remove().  Timers are all identical internally, so
1115       alarm_remove() will work with timer IDs returned by delay_set().
1116
1117       delay_remove_all is not needed
1118
1119       There is no delay_remove_all().  Timers are all identical internally,
1120       so alarm_remove_all() clears them all regardless how they were created.
1121
1122       Comparison
1123
1124       Below is a table to help compare the various delayed message-sending
1125       methods
1126
1127         +-----------+------------------+---------------------+------------+
1128         |           | time argument    | clears other events | returns on |
1129         | method    | passed to method | of the same name    | success    |
1130         +-----------+------------------+---------------------+------------+
1131         | delay_set | seconds from now | N                   | alarm_id   |
1132         | delay     | seconds from now | Y                   | 0 (false)  |
1133         | alarm_set | unix epoch time  | N                   | alarm_id   |
1134         | alarm     | unix epoch time  | Y                   | 0 (false)  |
1135         +-----------+------------------+---------------------+------------+
1136
1137   Session Identifiers (IDs and Aliases)
1138       A session may be referred to by its object references (either blessed
1139       or stringified), a session ID, or one or more symbolic names we call
1140       aliases.
1141
1142       Every session is represented by an object, so session references are
1143       fairly straightforward.  POE::Kernel may reference these objects.  For
1144       instance, post() may use $_[SENDER] as a destination:
1145
1146         POE::Session->create(
1147           inline_states => {
1148             _start => sub { $_[KERNEL]->alias_set("echoer") },
1149             ping => sub {
1150               $_[KERNEL]->post( $_[SENDER], "pong", @_[ARG0..$#_] );
1151             }
1152           }
1153         );
1154
1155       POE also recognized stringified Session objects for convenience and as
1156       a form of weak reference.  Here $_[SENDER] is wrapped in quotes to
1157       stringify it:
1158
1159         POE::Session->create(
1160           inline_states => {
1161             _start => sub { $_[KERNEL]->alias_set("echoer") },
1162             ping => sub {
1163               $_[KERNEL]->post( "$_[SENDER]", "pong", @_[ARG0..$#_] );
1164             }
1165           }
1166         );
1167
1168       Every session is assigned a unique ID at creation time.  No two active
1169       sessions will have the same ID, but IDs may be reused over time.  The
1170       combination of a kernel ID and a session ID should be sufficient as a
1171       global unique identifier.
1172
1173         POE::Session->create(
1174           inline_states => {
1175             _start => sub { $_[KERNEL]->alias_set("echoer") },
1176             ping => sub {
1177               $_[KERNEL]->delay(
1178                 pong_later => rand(5), $_[SENDER]->ID, @_[ARG0..$#_]
1179               );
1180             },
1181             pong_later => sub {
1182               $_[KERNEL]->post( $_[ARG0], "pong", @_[ARG1..$#_] );
1183             }
1184           }
1185         );
1186
1187       Kernels also maintain a global session namespace or dictionary from
1188       which may be used to map a symbolic aliases to a session. Once an alias
1189       is mapping has been created, that alias may be used to refer to the
1190       session wherever a session may be specified.
1191
1192       In the previous examples, each echoer service has set an "echoer"
1193       alias.  Another session can post a ping request to the echoer session
1194       by using that alias rather than a session object or ID.  For example:
1195
1196         POE::Session->create(
1197           inline_states => {
1198             _start => sub { $_[KERNEL]->post(echoer => ping => "whee!" ) },
1199             pong => sub { print "@_[ARG0..$#_]\n" }
1200           }
1201         );
1202
1203       A session with an alias will not stop until all other activity has
1204       stopped.  Aliases are treated as a kind of event watcher.  Events come
1205       from active sessions.  Aliases therefore become useless when there are
1206       no active sessions left.  Rather than leaving the program running in a
1207       "zombie" state, POE detects this deadlock condition and triggers a
1208       cleanup.  See "Signal Classes" for more information.
1209
1210       alias_set ALIAS
1211
1212       alias_set() maps an ALIAS in POE::Kernel's dictionary to the current
1213       session. The ALIAS may then be used nearly everywhere a session
1214       reference, stringified reference, or ID is expected.
1215
1216       Sessions may have more than one alias.  Each alias must be defined in a
1217       separate alias_set() call.  A single alias may not refer to more than
1218       one session.
1219
1220       Multiple alias examples are above.
1221
1222       alias_set() returns 0 on success, or a nonzero failure indicator:
1223       EEXIST ("File exists") indicates that the alias is already assigned to
1224       to a different session.
1225
1226       alias_remove ALIAS
1227
1228       alias_remove() removes an ALIAS for the current session from
1229       POE::Kernel's dictionary.  The ALIAS will no longer refer to the
1230       current session.  This does not negatively affect events already posted
1231       to POE's queue.  Alias resolution occurs at post() time, not at
1232       delivery time.
1233
1234         POE::Session->create(
1235           inline_states => {
1236             _start => sub {
1237               $_[KERNEL]->alias_set("short_window");
1238               $_[KERNEL]->delay(close_window => 1);
1239             },
1240             close_window => {
1241               $_[KERNEL]->alias_remove("short_window");
1242             }
1243           }
1244         );
1245
1246       alias_remove() returns 0 on success or a nonzero failure code:  ESRCH
1247       ("No such process") indicates that the ALIAS is not currently in
1248       POE::Kernel's dictionary.  EPERM ("Operation not permitted") means that
1249       the current session may not remove the ALIAS because it is in use by
1250       some other session.
1251
1252       alias_resolve ALIAS
1253
1254       alias_resolve() returns a session reference corresponding to a given
1255       ALIAS.  Actually, the ALIAS may be a stringified session reference, a
1256       session ID, or an alias previously registered by alias_set().
1257
1258       One use for alias_resolve() is to detect whether another session has
1259       gone away:
1260
1261         unless (defined $_[KERNEL]->alias_resolve("Elvis")) {
1262           print "Elvis has left the building.\n";
1263         }
1264
1265       As previously mentioned, alias_resolve() returns a session reference or
1266       undef on failure.  Failure also sets $! to ESRCH ("No such process")
1267       when the ALIAS is not currently in POE::Kernel's.
1268
1269       alias_list [SESSION_REFERENCE]
1270
1271       alias_list() returns a list of aliases associated with a specific
1272       SESSION, or with the current session if SESSION is omitted.
1273       alias_list() returns an empty list if the requested SESSION has no
1274       aliases.
1275
1276       SESSION may be a session reference (blessed or stringified), a session
1277       ID, or a session alias.
1278
1279         POE::Session->create(
1280           inline_states => {
1281             $_[KERNEL]->alias_set("mi");
1282             print(
1283               "The names I call myself: ",
1284               join(", ", $_[KERNEL]->alias_list()),
1285               "\n"
1286             );
1287           }
1288         );
1289
1290       ID_id_to_session SESSION_ID
1291
1292       ID_id_to_session() translates a session ID into a session reference.
1293       It's a special-purpose subset of alias_resolve(), so it's a little
1294       faster and somewhat less flexible.
1295
1296         unless (defined $_[KERNEL]->ID_id_to_session($session_id)) {
1297           print "Session $session_id doesn't exist.\n";
1298         }
1299
1300       ID_id_to_session() returns undef if a lookup failed.  $! will be set to
1301       ESRCH ("No such process").
1302
1303       ID_session_to_id SESSION_REFERENCE
1304
1305       ID_session_to_id() converts a blessed or stringified SESSION_REFERENCE
1306       into a session ID.  It's more practical for stringified references, as
1307       programs can call the POE::Session ID() method on the blessed ones.
1308       These statements are equivalent:
1309
1310         $id = $_[SENDER]->ID();
1311         $id = $_[KERNEL]->ID_session_to_id($_[SENDER]);
1312         $id = $_[KERNEL]->ID_session_to_id("$_[SENDER]");
1313
1314       As with other POE::Kernel lookup methods, ID_session_to_id() returns
1315       undef on failure, setting $! to ESRCH ("No such process").
1316
1317   I/O Watchers (Selects)
1318       No event system would be complete without the ability to asynchronously
1319       watch for I/O events.  POE::Kernel implements the lowest level
1320       watchers, which are called "selects" because they were historically
1321       implemented using Perl's built-in select(2) function.
1322
1323       Applications handle I/O readiness events by performing some activity on
1324       the underlying filehandle.  Read-readiness might be handled by reading
1325       from the handle.  Write-readiness by writing to it.
1326
1327       All I/O watcher events include two parameters.  "ARG0" contains the
1328       handle that is ready for work.  "ARG1" contains an integer describing
1329       what's ready.
1330
1331         sub handle_io {
1332           my ($handle, $mode) = @_[ARG0, ARG1];
1333           print "File $handle is ready for ";
1334           if ($mode == 0) {
1335             print "reading";
1336           }
1337           elsif ($mode == 1) {
1338             print "writing";
1339           }
1340           elsif ($mode == 2) {
1341             print "out-of-band reading";
1342           }
1343           else {
1344             die "unknown mode $mode";
1345           }
1346           print "\n";
1347           # ... do something here
1348         }
1349
1350       The remaining parameters, @_[ARG2..$%_], contain additional parameters
1351       that were passed to the POE::Kernel method that created the watcher.
1352
1353       POE::Kernel conditions filehandles to be 8-bit clean and non-blocking.
1354       Programs that need them conditioned differently should set them up
1355       after starting POE I/O watchers. If you are running a Perl older than
1356       5.8.1 and is using tied filehandles, you need to set non-blocking mode
1357       yourself as IO::Handle does not work well.  See
1358       <https://rt.cpan.org/Ticket/Display.html?id=67545> for more info.
1359
1360       I/O watchers will prevent sessions from stopping.
1361
1362       select_read FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]
1363
1364       select_read() starts or stops the current session from watching for
1365       incoming data on a given FILE_HANDLE.  The watcher is started if
1366       EVENT_NAME is specified, or stopped if it's not.
1367       ADDITIONAL_PARAMETERS, if specified, will be passed to the EVENT_NAME
1368       handler as @_[ARG2..$#_].
1369
1370         POE::Session->create(
1371           inline_states => {
1372             _start => sub {
1373               $_[HEAP]{socket} = IO::Socket::INET->new(
1374                 PeerAddr => "localhost",
1375                 PeerPort => 25,
1376               );
1377               $_[KERNEL]->select_read( $_[HEAP]{socket}, "got_input" );
1378               $_[KERNEL]->delay(timed_out => 1);
1379             },
1380             got_input => sub {
1381               my $socket = $_[ARG0];
1382               while (sysread($socket, my $buf = "", 8192)) {
1383                 print $buf;
1384               }
1385             },
1386             timed_out => sub {
1387               $_[KERNEL]->select_read( delete $_[HEAP]{socket} );
1388             },
1389           }
1390         );
1391
1392       select_read() does not return anything significant.
1393
1394       select_write FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]
1395
1396       select_write() follows the same semantics as select_read(), but it
1397       starts or stops a watcher that looks for write-readiness.  That is,
1398       when EVENT_NAME is delivered, it means that FILE_HANDLE is ready to be
1399       written to.
1400
1401       select_write() does not return anything significant.
1402
1403       select_expedite FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]
1404
1405       select_expedite() does the same sort of thing as select_read() and
1406       select_write(), but it watches a FILE_HANDLE for out-of-band data ready
1407       to be input from a FILE_HANDLE.  Hardly anybody uses this, but it
1408       exists for completeness' sake.
1409
1410       An EVENT_NAME event will be delivered whenever the FILE_HANDLE can be
1411       read from out-of-band.  Out-of-band data is considered "expedited"
1412       because it is often ahead of a socket's normal data.
1413
1414       select_expedite() does not return anything significant.
1415
1416       select_pause_read FILE_HANDLE
1417
1418       select_pause_read() is a lightweight way to pause a FILE_HANDLE input
1419       watcher without performing all the bookkeeping of a select_read().
1420       It's used with select_resume_read() to implement input flow control.
1421
1422       Input that occurs on FILE_HANDLE will backlog in the operating system
1423       buffers until select_resume_read() is called.
1424
1425       A side effect of bypassing the select_read() bookkeeping is that a
1426       paused FILE_HANDLE will not prematurely stop the current session.
1427
1428       select_pause_read() does not return anything significant.
1429
1430       select_resume_read FILE_HANDLE
1431
1432       select_resume_read() resumes a FILE_HANDLE input watcher that was
1433       previously paused by select_pause_read().  See select_pause_read() for
1434       more discussion on lightweight input flow control.
1435
1436       Data backlogged in the operating system due to a select_pause_read()
1437       call will become available after select_resume_read() is called.
1438
1439       select_resume_read() does not return anything significant.
1440
1441       select_pause_write FILE_HANDLE
1442
1443       select_pause_write() pauses a FILE_HANDLE output watcher the same way
1444       select_pause_read() does for input.  Please see select_pause_read() for
1445       further discussion.
1446
1447       select_resume_write FILE_HANDLE
1448
1449       select_resume_write() resumes a FILE_HANDLE output watcher the same way
1450       that select_resume_read() does for input.  See select_resume_read() for
1451       further discussion.
1452
1453       select FILE_HANDLE [, EV_READ [, EV_WRITE [, EV_EXPEDITE [, ARGS] ] ] ]
1454
1455       POE::Kernel's select() method sets or clears a FILE_HANDLE's read,
1456       write and expedite watchers at once.  It's a little more expensive than
1457       calling select_read(), select_write() and select_expedite() manually,
1458       but it's significantly more convenient.
1459
1460       Defined event names enable their corresponding watchers, and undefined
1461       event names disable them.  This turns off all the watchers for a
1462       FILE_HANDLE:
1463
1464         sub stop_io {
1465           $_[KERNEL]->select( $_[HEAP]{file_handle} );
1466         }
1467
1468       This statement:
1469
1470         $_[KERNEL]->select( $file_handle, undef, "write_event", undef, @stuff );
1471
1472       is equivalent to:
1473
1474         $_[KERNEL]->select_read( $file_handle );
1475         $_[KERNEL]->select_write( $file_handle, "write_event", @stuff );
1476         $_[KERNEL]->select_expedite( $file_handle );
1477
1478       POE::Kernel's select() should not be confused with Perl's built-in
1479       select() function.
1480
1481       As with the other I/O watcher methods, select() does not return a
1482       meaningful value.
1483
1484   Session Management
1485       Sessions are dynamic.  They may be created and destroyed during a
1486       program's lifespan.  When a session is created, it becomes the "child"
1487       of the current session.  The creator -- the current session -- becomes
1488       its "parent" session.  This is loosely modeled after UNIX processes.
1489
1490       The most common session management is done by creating new sessions and
1491       allowing them to eventually stop.
1492
1493       Every session has a parent, even the very first session created.
1494       Sessions without obvious parents are children of the program's
1495       POE::Kernel instance.
1496
1497       Child sessions will keep their parents active.  See "Session Lifespans"
1498       for more about why sessions stay alive.
1499
1500       The parent/child relationship tree also governs the way many signals
1501       are dispatched.  See "Common Signal Dispatching" for more information
1502       on that.
1503
1504       Session Management Events (_start, _stop, _parent, _child)
1505
1506       POE::Kernel provides four session management events: _start, _stop,
1507       _parent and _child.  They are invoked synchronously whenever a session
1508       is newly created or just about to be destroyed.
1509
1510       _start
1511         _start should be familiar by now.  POE dispatches the _start event to
1512         initialize a session after it has been registered under POE::Kernel.
1513         What is not readily apparent, however, is that it is invoked before
1514         the POE::Session constructor returns.
1515
1516         Within the _start handler, the event's sender is the session that
1517         created the new session.  Otherwise known as the new session's
1518         parent.  Sessions created before POE::Kernel->run() is called will be
1519         descendents of the program's POE::Kernel singleton.
1520
1521         The _start handler's return value is passed to the parent session in
1522         a _child event, along with the notification that the parent's new
1523         child was created successfully.  See the discussion of _child for
1524         more details.
1525
1526           POE::Session->create(
1527             inline_states => { _start=> \&_start },
1528             args => [ $some, $args ]
1529           );
1530
1531           sub _start {
1532             my ( $some, $args ) = @_[ ARG0, ARG1 ];
1533             # ....
1534           }
1535
1536       _stop
1537         _stop is a little more mysterious.  POE calls a _stop handler when a
1538         session is irrevocably about to be destroyed.  Part of session
1539         destruction is the forcible reclamation of its resources (events,
1540         timers, message events, etc.) so it's not possible to post() a
1541         message from _stop's handler.  A program is free to try, but the
1542         event will be destroyed before it has a chance to be dispatched.
1543
1544         the _stop handler's return value is passed to the parent's _child
1545         event.  See _child for more details.
1546
1547         _stop is usually invoked when a session has no further reason to
1548         live, although signals may cause them to stop sooner.
1549
1550         The corresponding _child handler is invoked synchronously just after
1551         _stop returns.
1552
1553       _parent
1554         _parent is used to notify a child session when its parent has
1555         changed.  This usually happens when a session is first created.  It
1556         can also happen when a child session is detached from its parent. See
1557         detach_child and "detach_myself".
1558
1559         _parent's ARG0 contains the session's previous parent, and ARG1
1560         contains its new parent.
1561
1562           sub _parent {
1563             my ( $old_parent, $new_parent ) = @_[ ARG0, ARG1 ];
1564             print(
1565               "Session ", $_[SESSION]->ID,
1566               " parent changed from session ", $old_parent->ID,
1567               " to session ", $new_parent->ID,
1568               "\n"
1569             );
1570           }
1571
1572       _child
1573         _child notifies one session when a child session has been created,
1574         destroyed, or reassigned to or from another parent.  It's usually
1575         dispatched when sessions are created or destroyed.  It can also
1576         happen when a session is detached from its parent.
1577
1578         _child includes some information in the "arguments" portion of @_.
1579         Typically ARG0, ARG1 and ARG2, but these may be overridden by a
1580         different POE::Session class:
1581
1582         ARG0 contains a string describing what has happened to the child.
1583         The string may be 'create' (the child session has been created),
1584         'gain' (the child has been given by another session), or 'lose' (the
1585         child session has stopped or been given away).
1586
1587         In all cases, ARG1 contains a reference to the child session.
1588
1589         In the 'create' case, ARG2 holds the value returned by the child
1590         session's _start handler.  Likewise, ARG2 holds the _stop handler's
1591         return value for the 'lose' case.
1592
1593           sub _child {
1594             my( $reason, $child ) = @_[ ARG0, ARG1 ];
1595             if( $reason eq 'create' ) {
1596               my $retval = $_[ ARG2 ];
1597             }
1598             # ...
1599           }
1600
1601       The events are delivered in specific orders.
1602
1603       When a new session is created:
1604
1605       1.  The session's constructor is called.
1606
1607       2.  The session is put into play.  That is, POE::Kernel enters the
1608           session into its bookkeeping.
1609
1610       3.  The new session receives _start.
1611
1612       4.  The parent session receives _child ('create'), the new session
1613           reference, and the new session's _start's return value.
1614
1615       5.  The session's constructor returns.
1616
1617       When an old session stops:
1618
1619       1.  If the session has children of its own, they are given to the
1620           session's parent.  This triggers one or more _child ('gain') events
1621           in the parent, and a _parent in each child.
1622
1623       2.  Once divested of its children, the stopping session receives a
1624           _stop event.
1625
1626       3.  The stopped session's parent receives a _child ('lose') event with
1627           the departing child's reference and _stop handler's return value.
1628
1629       4.  The stopped session is removed from play, as are all its remaining
1630           resources.
1631
1632       5.  The parent session is checked for idleness.  If so, garbage
1633           collection will commence on it, and it too will be stopped
1634
1635       When a session is detached from its parent:
1636
1637       1.  The parent session of the session being detached is notified with a
1638           _child ('lose') event.  The _stop handler's return value is undef
1639           since the child is not actually stopping.
1640
1641       2.  The detached session is notified with a _parent event that its new
1642           parent is POE::Kernel itself.
1643
1644       3.  POE::Kernel's bookkeeping data is adjusted to reflect the change of
1645           parentage.
1646
1647       4.  The old parent session is checked for idleness.  If so, garbage
1648           collection will commence on it, and it too will be stopped
1649
1650       Session Management Methods
1651
1652       These methods allow sessions to be detached from their parents in the
1653       rare cases where the parent/child relationship gets in the way.
1654
1655       detach_child CHILD_SESSION
1656
1657       detach_child() detaches a particular CHILD_SESSION from the current
1658       session.  On success, the CHILD_SESSION will become a child of the
1659       POE::Kernel instance, and detach_child() will return true.  On failure
1660       however, detach_child() returns false and sets $! to explain the nature
1661       of the failure:
1662
1663       ESRCH ("No such process").
1664           The CHILD_SESSION is not a valid session.
1665
1666       EPERM ("Operation not permitted").
1667           The CHILD_SESSION exists, but it is not a child of the current
1668           session.
1669
1670       detach_child() will generate "_parent" and/or "_child" events to the
1671       appropriate sessions.  See Session Management Events for a detailed
1672       explanation of these events.  See above for the order the events are
1673       generated.
1674
1675       detach_myself
1676
1677       detach_myself() detaches the current session from its current parent.
1678       The new parent will be the running POE::Kernel instance.  It returns
1679       true on success.  On failure it returns false and sets $! to explain
1680       the nature of the failure:
1681
1682       EPERM ("Operation not permitted").
1683           The current session is already a child of POE::Kernel, so it may
1684           not be detached.
1685
1686       detach_child() will generate "_parent" and/or "_child" events to the
1687       appropriate sessions.  See Session Management Events for a detailed
1688       explanation of these events.  See above for the order the events are
1689       generated.
1690
1691   Signals
1692       POE::Kernel provides methods through which a program can register
1693       interest in signals that come along, can deliver its own signals
1694       without resorting to system calls, and can indicate that signals have
1695       been handled so that default behaviors are not necessary.
1696
1697       Signals are action at a distance by nature, and their implementation
1698       requires widespread synchronization between sessions (and reentrancy in
1699       the dispatcher, but that's an implementation detail).  Perfecting the
1700       semantics has proven difficult, but POE tries to do the Right Thing
1701       whenever possible.
1702
1703       POE does not register %SIG handlers for signals until sig() is called
1704       to watch for them.  Therefore a signal's default behavior occurs for
1705       unhandled signals.  That is, SIGINT will gracelessly stop a program,
1706       SIGWINCH will do nothing, SIGTSTP will pause a program, and so on.
1707
1708       Signal Classes
1709
1710       There are three signal classes.  Each class defines a default behavior
1711       for the signal and whether the default can be overridden.  They are:
1712
1713       Benign, advisory, or informative signals
1714
1715       These are three names for the same signal class.  Signals in this class
1716       notify a session of an event but do not terminate the session if they
1717       are not handled.
1718
1719       It is possible for an application to create its own benign signals.
1720       See "signal" below.
1721
1722       Terminal signals
1723
1724       Terminal signals will kill sessions if they are not handled by a
1725       "sig_handled"() call.  The OS signals that usually kill or dump a
1726       process are considered terminal in POE, but they never trigger a
1727       coredump.  These are: HUP, INT, QUIT and TERM.
1728
1729       There are two terminal signals created by and used within POE:
1730
1731       DIE "DIE" notifies sessions that a Perl exception has occurred.  See
1732           "Exception Handling" for details.
1733
1734       IDLE
1735           The "IDLE" signal is used to notify leftover sessions that a
1736           program has run out of things to do.
1737
1738       Nonmaskable signals
1739
1740       Nonmaskable signals are terminal regardless whether sig_handled() is
1741       called.  The term comes from "NMI", the non-maskable CPU interrupt
1742       usually generated by an unrecoverable hardware exception.
1743
1744       Sessions that receive a non-maskable signal will unavoidably stop.  POE
1745       implements two non-maskable signals:
1746
1747       ZOMBIE
1748           This non-maskable signal is fired if a program has received an
1749           "IDLE" signal but neither restarted nor exited.  The program has
1750           become a zombie (that is, it's neither dead nor alive, and only
1751           exists to consume braaaains ...er...  memory).  The "ZOMBIE" signal
1752           acts like a cricket bat to the head, bringing the zombie down, for
1753           good.
1754
1755       UIDESTROY
1756           This non-maskable signal indicates that a program's user interface
1757           has been closed, and the program should take the user's hint and
1758           buzz off as well.  It's usually generated when a particular GUI
1759           widget is closed.
1760
1761       Common Signal Dispatching
1762
1763       Most signals are not dispatched to a single session.  POE's session
1764       lineage (parents and children) form a sort of family tree.  When a
1765       signal is sent to a session, it first passes through any children (and
1766       grandchildren, and so on) that are also interested in the signal.
1767
1768       In the case of terminal signals, if any of the sessions a signal passes
1769       through calls "sig_handled"(), then the signal is considered taken care
1770       of.  However if none of them do, then the entire session tree rooted at
1771       the destination session is terminated.  For example, consider this tree
1772       of sessions:
1773
1774         POE::Kernel
1775           Session 2
1776             Session 4
1777             Session 5
1778           Session 3
1779             Session 6
1780             Session 7
1781
1782       POE::Kernel is the parent of sessions 2 and 3.  Session 2 is the parent
1783       of sessions 4 and 5.  And session 3 is the parent of 6 and 7.
1784
1785       A signal sent to Session 2 may also be dispatched to session 4 and 5
1786       because they are 2's children.  Sessions 4 and 5 will only receive the
1787       signal if they have registered the appropriate watcher.  If the signal
1788       is terminal, and none of the signal watchers in sessions 2, 4 and 5
1789       called "sig_handled()", all 3 sessions will be terminated.
1790
1791       The program's POE::Kernel instance is considered to be a session for
1792       the purpose of signal dispatch.  So any signal sent to POE::Kernel will
1793       propagate through every interested session in the entire program.  This
1794       is in fact how OS signals are handled: A global signal handler is
1795       registered to forward the signal to POE::Kernel.
1796
1797       Signal Semantics
1798
1799       All signals come with the signal name in ARG0.  The signal name is as
1800       it appears in %SIG, with one exception: Child process signals are
1801       always "CHLD" even if the current operating system recognizes them as
1802       "CLD".
1803
1804       Certain signals have special semantics:
1805
1806       SIGCHLD
1807
1808       SIGCLD
1809
1810       Both "SIGCHLD" and "SIGCLD" indicate that a child process has exited or
1811       been terminated by some signal.  The actual signal name varies between
1812       operating systems, but POE uses "CHLD" regardless.
1813
1814       Interest in "SIGCHLD" is registered using the "sig_child" method.  The
1815       "sig"() method also works, but it's not as nice.
1816
1817       The "SIGCHLD" event includes three parameters:
1818
1819       ARG0
1820           "ARG0" contains the string 'CHLD' (even if the OS calls it SIGCLD,
1821           SIGMONKEY, or something else).
1822
1823       ARG1
1824           "ARG1" contains the process ID of the finished child process.
1825
1826       ARG2
1827           And "ARG2" holds the value of $? for the finished process.
1828
1829       Example:
1830
1831         sub sig_CHLD {
1832           my( $name, $PID, $exit_val ) = @_[ ARG0, ARG1, ARG2 ];
1833           # ...
1834         }
1835
1836       SIGPIPE
1837
1838       SIGPIPE is rarely used since POE provides events that do the same
1839       thing.  Nevertheless SIGPIPE is supported if you need it.  Unlike most
1840       events, however, SIGPIPE is dispatched directly to the active session
1841       when it's caught.  Barring race conditions, the active session should
1842       be the one that caused the OS to send the signal in the first place.
1843
1844       The SIGPIPE signal will still propagate to child sessions.
1845
1846       ARG0 is "PIPE".  There is no other information associated with this
1847       signal.
1848
1849       SIGWINCH
1850
1851       Window resizes can generate a large number of signals very quickly.
1852       This may not be a problem when using perl 5.8.0 or later, but earlier
1853       versions may not take kindly to such abuse.  You have been warned.
1854
1855       ARG0 is "WINCH".  There is no other information associated with this
1856       signal.
1857
1858       Exception Handling
1859
1860       POE::Kernel provides only one form of exception handling: the "DIE"
1861       signal.
1862
1863       When exception handling is enabled (the default), POE::Kernel wraps
1864       state invocation in "eval{}".  If the event handler raises an
1865       exception, generally with "die", POE::Kernel will dispatch a "DIE"
1866       signal to the event's destination session.
1867
1868       "ARG0" is the signal name, "DIE".
1869
1870       "ARG1" is a hashref describing the exception:
1871
1872       error_str
1873           The text of the exception.  In other words, $@.
1874
1875       dest_session
1876           Session object of the state that the raised the exception.  In
1877           other words, $_[SESSION] in the function that died.
1878
1879       event
1880           Name of the event that died.
1881
1882       source_session
1883           Session object that sent the original event.  That is, $_[SENDER]
1884           in the function that died.
1885
1886       from_state
1887           State from which the original event was sent.  That is,
1888           $_[CALLER_STATE] in the function that died.
1889
1890       file
1891           Name of the file the event was sent from.  That is, $_[CALLER_FILE]
1892           in the function that died.
1893
1894       line
1895           Line number the event was sent from.  That is, $_[CALLER_LINE] in
1896           the function that died.
1897
1898       Note that the preceding discussion assumes you are using POE::Session's
1899       call semantics.
1900
1901       Note that the "DIE" signal is sent to the session that raised the
1902       exception, not the session that sent the event that caused the
1903       exception to be raised.
1904
1905         sub _start {
1906           $poe_kernel->sig( DIE => 'sig_DIE' );
1907           $poe_kernel->yield( 'some_event' );
1908         }
1909
1910         sub some_event {
1911           die "I didn't like that!";
1912         }
1913
1914         sub sig_DIE {
1915           my( $sig, $ex ) = @_[ ARG0, ARG1 ];
1916           # $sig is 'DIE'
1917           # $ex is the exception hash
1918           warn "$$: error in $ex->{event}: $ex->{error_str}";
1919           $poe_kernel->sig_handled();
1920
1921           # Send the signal to session that sent the original event.
1922           if( $ex->{source_session} ne $_[SESSION] ) {
1923             $poe_kernel->signal( $ex->{source_session}, 'DIE', $sig, $ex );
1924           }
1925         }
1926
1927       POE::Kernel's built-in exception handling can be disabled by setting
1928       the "POE::Kernel::CATCH_EXCEPTIONS" constant to zero.  As with other
1929       compile-time configuration constants, it must be set before POE::Kernel
1930       is compiled:
1931
1932         BEGIN {
1933           package POE::Kernel;
1934           use constant CATCH_EXCEPTIONS => 0;
1935         }
1936         use POE;
1937
1938       or
1939
1940         sub POE::Kernel::CATCH_EXCEPTIONS () { 0 }
1941         use POE;
1942
1943   Signal Watcher Methods
1944       And finally the methods themselves.
1945
1946       sig SIGNAL_NAME [, EVENT_NAME [, LIST] ]
1947
1948       sig() registers or unregisters an EVENT_NAME event for a particular
1949       SIGNAL_NAME, with an optional LIST of parameters that will be passed to
1950       the signal's handler---after any data that comes wit the signal.
1951
1952       If EVENT_NAME is defined, the signal handler is registered.  Otherwise
1953       it's unregistered.
1954
1955       Each session can register only one handler per SIGNAL_NAME.  Subsequent
1956       registrations will replace previous ones.  Multiple sessions may
1957       however watch the same signal.
1958
1959       SIGNAL_NAMEs are generally the same as members of %SIG, with two
1960       exceptions.  First, "CLD" is an alias for "CHLD" (although see
1961       "sig_child").  And second, it's possible to send and handle signals
1962       created by the application and have no basis in the operating system.
1963
1964         sub handle_start {
1965           $_[KERNEL]->sig( INT => "event_ui_shutdown" );
1966           $_[KERNEL]->sig( bat => "holy_searchlight_batman" );
1967           $_[KERNEL]->sig( signal => "main_screen_turn_on" );
1968         }
1969
1970       The operating system may never be able to generate the last two
1971       signals, but a POE session can by using POE::Kernel's "signal"()
1972       method.
1973
1974       Later on the session may decide not to handle the signals:
1975
1976         sub handle_ui_shutdown {
1977           $_[KERNEL]->sig( "INT" );
1978           $_[KERNEL]->sig( "bat" );
1979           $_[KERNEL]->sig( "signal" );
1980         }
1981
1982       More than one session may register interest in the same signal, and a
1983       session may clear its own signal watchers without affecting those in
1984       other sessions.
1985
1986       sig() does not return a meaningful value.
1987
1988       sig_child PROCESS_ID [, EVENT_NAME [, LIST] ]
1989
1990       sig_child() is a convenient way to deliver an EVENT_NAME event when a
1991       particular PROCESS_ID has exited.  An optional LIST of parameters will
1992       be passed to the signal handler after the waitpid() information.
1993
1994       The watcher can be cleared at any time by calling sig_child() with just
1995       the PROCESS_ID.
1996
1997       A session may register as many sig_child() handlers as necessary, but a
1998       session may only have one per PROCESS_ID.
1999
2000       sig_child() watchers are one-shot.  They automatically unregister
2001       themselves once the EVENT_NAME has been delivered.  There's no point in
2002       continuing to watch for a signal that will never come again.  Other
2003       signal handlers persist until they are cleared.
2004
2005       sig_child() watchers keep a session alive for as long as they are
2006       active.  This is unique among POE's signal watchers.
2007
2008       Programs that wish to reliably reap child processes should be sure to
2009       call sig_child() before returning from the event handler that forked
2010       the process.  Otherwise POE::Kernel may have an opportunity to call
2011       waitpid() before an appropriate event watcher has been registered.
2012
2013       Programs that reap processes with waitpid() must clear POE's watchers
2014       for the same process IDs, otherwise POE will wait indefinitely for
2015       processes that never send signals.
2016
2017       sig_child() does not return a meaningful value.
2018
2019         sub forked_parent {
2020           my( $heap, $pid, $details ) = @_[ HEAP, ARG0, ARG1 ];
2021           $poe_kernel->sig_child( $pid, 'sig_child', $details );
2022         }
2023
2024         sub sig_child {
2025           my( $heap, $sig, $pid, $exit_val, $details ) = @_[ HEAP, ARG0..ARG3 ];
2026           my $details = delete $heap->{ $pid };
2027           warn "$$: Child $pid exited"
2028           # .... also, $details has been passed from forked_parent()
2029           # through sig_child()
2030         }
2031
2032       sig_handled
2033
2034       sig_handled() informs POE::Kernel that the currently dispatched signal
2035       has been handled by the currently active session. If the signal is
2036       terminal, the sig_handled() call prevents POE::Kernel from stopping the
2037       sessions that received the signal.
2038
2039       A single signal may be dispatched to several sessions.  Only one needs
2040       to call sig_handled() to prevent the entire group from being stopped.
2041       If none of them call it, however, then they are all stopped together.
2042
2043       sig_handled() does not return a meaningful value.
2044
2045         sub _start {
2046           $_[KERNEL]->sig( INT => 'sig_INT' );
2047         }
2048
2049         sub sig_INT {
2050           warn "$$ SIGINT";
2051           $_[KERNEL]->sig_handled();
2052         }
2053
2054       signal SESSION, SIGNAL_NAME [, ARGS_LIST]
2055
2056       signal() posts a SIGNAL_NAME signal to a specific SESSION with an
2057       optional ARGS_LIST that will be passed to every interested handler.  As
2058       mentioned elsewhere, the signal may be delivered to SESSION's children,
2059       grandchildren, and so on.  And if SESSION is the POE::Kernel itself,
2060       then all interested sessions will receive the signal.
2061
2062       It is possible to send a signal in POE that doesn't exist in the
2063       operating system.  signal() places the signal directly into POE's event
2064       queue as if they came from the operating system, but they are not
2065       limited to signals recognized by kill().  POE uses a few of these
2066       fictitious signals for its own global notifications.
2067
2068       For example:
2069
2070         sub some_event_handler {
2071           # Turn on all main screens.
2072           $_[KERNEL]->signal( $_[KERNEL], "signal" );
2073         }
2074
2075       signal() returns true on success.  On failure, it returns false after
2076       setting $! to explain the nature of the failure:
2077
2078       ESRCH ("No such process")
2079           The SESSION does not exist.
2080
2081       Because all sessions are a child of POE::Kernel, sending a signal to
2082       the kernel will propagate the signal to all sessions.  This is a cheap
2083       form of multicast.
2084
2085         $_[KERNEL]->signal( $_[KERNEL], 'shutdown' );
2086
2087       signal_ui_destroy WIDGET_OBJECT
2088
2089       signal_ui_destroy() associates the destruction of a particular
2090       WIDGET_OBJECT with the complete destruction of the program's user
2091       interface.  When the WIDGET_OBJECT destructs, POE::Kernel issues the
2092       non-maskable UIDESTROY signal, which quickly triggers mass destruction
2093       of all active sessions.  POE::Kernel->run() returns shortly thereafter.
2094
2095         sub setup_ui {
2096           $_[HEAP]{main_widget} = Gtk->new("toplevel");
2097           # ... populate the main widget here ...
2098           $_[KERNEL]->signal_ui_destroy( $_[HEAP]{main_widget} );
2099         }
2100
2101       Detecting widget destruction is specific to each toolkit.
2102
2103   Event Handler Management
2104       Event handler management methods let sessions hot swap their event
2105       handlers at run time. For example, the POE::Wheel objects use state()
2106       to dynamically mix their own event handlers into the sessions that
2107       create them.
2108
2109       These methods only affect the current session; it would be rude to
2110       change another session's handlers.
2111
2112       There is only one method in this group.  Since it may be called in
2113       several different ways, it may be easier to understand if each is
2114       documented separately.
2115
2116       state EVENT_NAME [, CODE_REFERNCE]
2117
2118       state() sets or removes a handler for EVENT_NAME in the current
2119       session.  The function referred to by CODE_REFERENCE will be called
2120       whenever EVENT_NAME events are dispatched to the current session.  If
2121       CODE_REFERENCE is omitted, the handler for EVENT_NAME will be removed.
2122
2123       A session may only have one handler for a given EVENT_NAME.  Subsequent
2124       attempts to set an EVENT_NAME handler will replace earlier handlers
2125       with the same name.
2126
2127         # Stop paying attention to input.  Say goodbye, and
2128         # trigger a socket close when the message is sent.
2129         sub send_final_response {
2130           $_[HEAP]{wheel}->put("KTHXBYE");
2131           $_[KERNEL]->state( 'on_client_input' );
2132           $_[KERNEL]->state( on_flush => \&close_connection );
2133         }
2134
2135       state EVENT_NAME [, OBJECT_REFERENCE [, OBJECT_METHOD_NAME] ]
2136
2137       Set or remove a handler for EVENT_NAME in the current session.  If an
2138       OBJECT_REFERENCE is given, that object will handle the event.  An
2139       optional OBJECT_METHOD_NAME may be provided.  If the method name is not
2140       given, POE will look for a method matching the EVENT_NAME instead.  If
2141       the OBJECT_REFERENCE is omitted, the handler for EVENT_NAME will be
2142       removed.
2143
2144       A session may only have one handler for a given EVENT_NAME.  Subsequent
2145       attempts to set an EVENT_NAME handler will replace earlier handlers
2146       with the same name.
2147
2148         $_[KERNEL]->state( 'some_event', $self );
2149         $_[KERNEL]->state( 'other_event', $self, 'other_method' );
2150
2151       state EVENT_NAME [, CLASS_NAME [, CLASS_METHOD_NAME] ]
2152
2153       This form of state() call is virtually identical to that of the object
2154       form.
2155
2156       Set or remove a handler for EVENT_NAME in the current session.  If an
2157       CLASS_NAME is given, that class will handle the event.  An optional
2158       CLASS_METHOD_NAME may be provided.  If the method name is not given,
2159       POE will look for a method matching the EVENT_NAME instead.  If the
2160       CLASS_NAME is omitted, the handler for EVENT_NAME will be removed.
2161
2162       A session may only have one handler for a given EVENT_NAME.  Subsequent
2163       attempts to set an EVENT_NAME handler will replace earlier handlers
2164       with the same name.
2165
2166         $_[KERNEL]->state( 'some_event', __PACKAGE__ );
2167         $_[KERNEL]->state( 'other_event', __PACKAGE__, 'other_method' );
2168
2169   Public Reference Counters
2170       The methods in this section manipulate reference counters on the
2171       current session or another session.
2172
2173       Each session has a namespace for user-manipulated reference counters.
2174       These namespaces are associated with the target SESSION_ID for the
2175       reference counter methods, not the caller.  Nothing currently prevents
2176       one session from decrementing a reference counter that was incremented
2177       by another, but this behavior is not guaranteed to remain.  For now,
2178       it's up to the users of these methods to choose obscure counter names
2179       to avoid conflicts.
2180
2181       Reference counting is a big part of POE's magic.  Various objects
2182       (mainly event watchers and components) hold references to the sessions
2183       that own them.  "Session Lifespans" explains the concept in more
2184       detail.
2185
2186       The ability to keep a session alive is sometimes useful in an
2187       application or library.  For example, a component may hold a public
2188       reference to another session while it processes a request from that
2189       session.  In doing so, the component guarantees that the requester is
2190       still around when a response is eventually ready.  Keeping a reference
2191       to the session's object is not enough.  POE::Kernel has its own
2192       internal reference counting mechanism.
2193
2194       refcount_increment SESSION_ID, COUNTER_NAME
2195
2196       refcount_increment() increases the value of the COUNTER_NAME reference
2197       counter for the session identified by a SESSION_ID.  To discourage the
2198       use of session references, the refcount_increment() target session must
2199       be specified by its session ID.
2200
2201       The target session will not stop until the value of any and all of its
2202       COUNTER_NAME reference counters are zero.  (Actually, it may stop in
2203       some cases, such as failing to handle a terminal signal.)
2204
2205       Negative reference counters are legal.  They still must be incremented
2206       back to zero before a session is eligible for stopping.
2207
2208         sub handle_request {
2209           # Among other things, hold a reference count on the sender.
2210           $_[KERNEL]->refcount_increment( $_[SENDER]->ID, "pending request");
2211           $_[HEAP]{requesters}{$request_id} = $_[SENDER]->ID;
2212         }
2213
2214       For this to work, the session needs a way to remember the
2215       $_[SENDER]->ID for a given request.  Customarily the session generates
2216       a request ID and uses that to track the request until it is fulfilled.
2217
2218       refcount_increment() returns the resulting reference count (which may
2219       be zero) on success.  On failure, it returns undef and sets $! to be
2220       the reason for the error.
2221
2222       ESRCH: The SESSION_ID does not refer to a currently active session.
2223
2224       refcount_decrement SESSION_ID, COUNTER_NAME
2225
2226       refcount_decrement() reduces the value of the COUNTER_NAME reference
2227       counter for the session identified by a SESSION_ID.  It is the
2228       counterpoint for refcount_increment().  Please see refcount_increment()
2229       for more context.
2230
2231         sub finally_send_response {
2232           # Among other things, release the reference count for the
2233           # requester.
2234           my $requester_id = delete $_[HEAP]{requesters}{$request_id};
2235           $_[KERNEL]->refcount_decrement( $requester_id, "pending request");
2236         }
2237
2238       The requester's $_[SENDER]->ID is remembered and removed from the heap
2239       (lest there be memory leaks).  It's used to decrement the reference
2240       counter that was incremented at the start of the request.
2241
2242       refcount_decrement() returns the resulting reference count (which may
2243       be zero) on success.  On failure, it returns undef, and $! will be set
2244       to the reason for the failure:
2245
2246       ESRCH: The SESSION_ID does not refer to a currently active session.
2247
2248       It is not possible to discover currently active public references.  See
2249       POE::API::Peek.
2250
2251   Kernel State Accessors
2252       POE::Kernel provides a few accessors into its massive brain so that
2253       library developers may have convenient access to necessary data without
2254       relying on their callers to provide it.
2255
2256       These accessors expose ways to break session encapsulation.  Please use
2257       them sparingly and carefully.
2258
2259       get_active_session
2260
2261       get_active_session() returns a reference to the session that is
2262       currently running, or a reference to the program's POE::Kernel instance
2263       if no session is running at that moment.  The value is equivalent to
2264       POE::Session's $_[SESSION].
2265
2266       This method was added for libraries that need $_[SESSION] but don't
2267       want to include it as a parameter in their APIs.
2268
2269         sub some_housekeeping {
2270           my( $self ) = @_;
2271           my $session = $poe_kernel->get_active_session;
2272           # do some housekeeping on $session
2273         }
2274
2275       get_active_event
2276
2277       get_active_event() returns the name of the event currently being
2278       dispatched.  It returns an empty string when called outside event
2279       dispatch.  The value is equivalent to POE::Session's $_[STATE].
2280
2281         sub waypoint {
2282           my( $message ) = @_;
2283           my $event = $poe_kernel->get_active_event;
2284           print STDERR "$$:$event:$mesage\n";
2285         }
2286
2287       get_event_count
2288
2289       get_event_count() returns the number of events pending in POE's event
2290       queue.  It is exposed for POE::Loop class authors.  It may be
2291       deprecated in the future.
2292
2293       get_next_event_time
2294
2295       get_next_event_time() returns the time the next event is due, in a form
2296       compatible with the UNIX time() function.  It is exposed for POE::Loop
2297       class authors.  It may be deprecated in the future.
2298
2299       poe_kernel_loop
2300
2301       poe_kernel_loop() returns the name of the POE::Loop class that is used
2302       to detect and dispatch events.
2303
2304   Session Helper Methods
2305       The methods in this group expose features for POE::Session class
2306       authors.
2307
2308       session_alloc SESSION_OBJECT [, START_ARGS]
2309
2310       session_alloc() allocates a session context within POE::Kernel for a
2311       newly created SESSION_OBJECT.  A list of optional START_ARGS will be
2312       passed to the session as part of the "_start" event.
2313
2314       The SESSION_OBJECT is expected to follow a subset of POE::Session's
2315       interface.
2316
2317       There is no session_free().  POE::Kernel determines when the session
2318       should stop and performs the necessary cleanup after dispatching _stop
2319       to the session.
2320
2321   Miscellaneous Methods
2322       We don't know where to classify the methods in this section.
2323
2324       new
2325
2326       It is not necessary to call POE::Kernel's new() method.  Doing so will
2327       return the program's singleton POE::Kernel object, however.
2328

PUBLIC EXPORTED VARIABLES

2330       POE::Kernel exports two variables for your coding enjoyment:
2331       $poe_kernel and $poe_main_window.  POE::Kernel is implicitly used by
2332       POE itself, so using POE gets you POE::Kernel (and its exports) for
2333       free.
2334
2335       In more detail:
2336
2337   $poe_kernel
2338       $poe_kernel contains a reference to the process' POE::Kernel singleton
2339       instance. It's mainly used for accessing POE::Kernel methods from
2340       places where $_[KERNEL] is not available.  It's most commonly used in
2341       helper libraries.
2342
2343   $poe_main_window
2344       $poe_main_window is used by graphical toolkits that require at least
2345       one widget to be created before their event loops are usable.  This is
2346       currently only Tk.
2347
2348       POE::Loop::Tk creates a main window to satisfy Tk's event loop.  The
2349       window is given to the application since POE has no other use for it.
2350
2351       $poe_main_window is undefined in toolkits that don't require a widget
2352       to dispatch events.
2353
2354       On a related note, POE will shut down if the widget in $poe_main_window
2355       is destroyed.  This can be changed with POE::Kernel's
2356       "signal_ui_destroy" method.
2357

DEBUGGING POE AND PROGRAMS USING IT

2359       POE includes quite a lot of debugging code, in the form of both fatal
2360       assertions and run-time traces.  They may be enabled at compile time,
2361       but there is no way to toggle them at run-time.  This was done to avoid
2362       run-time penalties in programs where debugging is not necessary.  That
2363       is, in most production cases.
2364
2365       Traces are verbose reminders of what's going on within POE.  Each is
2366       prefixed with a four-character field describing the POE subsystem that
2367       generated it.
2368
2369       Assertions (asserts) are quiet but deadly, both in performance (they
2370       cause a significant run-time performance hit) and because they cause
2371       fatal errors when triggered.
2372
2373       The assertions and traces are useful for developing programs with POE,
2374       but they were originally added to debug POE itself.
2375
2376       Each assertion and tracing group is enabled by setting a constant in
2377       the POE::Kernel namespace to a true value.
2378
2379         BEGIN {
2380           package POE::Kernel;
2381           use constant ASSERT_DEFAULT => 1;
2382         }
2383         use POE;
2384
2385       Or the old-fashioned (and more concise) "constant subroutine" method.
2386       This doesn't need the "BEGIN{}" block since subroutine definitions are
2387       done at compile time.
2388
2389         sub POE::Kernel::ASSERT_DEFAULT () { 1 }
2390         use POE;
2391
2392       The switches must be defined as constants before POE::Kernel is first
2393       loaded.  Otherwise Perl's compiler will not see the constants when
2394       first compiling POE::Kernel, and the features will not be properly
2395       enabled.
2396
2397       Assertions and traces may also be enabled by setting shell environment
2398       variables.  The environment variables are named after the POE::Kernel
2399       constants with a "POE_" prefix.
2400
2401         POE_ASSERT_DEFAULT=1 POE_TRACE_DEFAULT=1 ./my_poe_program
2402
2403       In alphabetical order:
2404
2405   ASSERT_DATA
2406       ASSERT_DATA enables run-time data integrity checks within POE::Kernel
2407       and the classes that mix into it.  POE::Kernel tracks a lot of cross-
2408       referenced data, and this group of assertions ensures that it's
2409       consistent.
2410
2411       Prefix: <dt>
2412
2413       Environment variable: POE_ASSERT_DATA
2414
2415   ASSERT_DEFAULT
2416       ASSERT_DEFAULT specifies the default value for assertions that are not
2417       explicitly enabled or disabled.  This is a quick and reliable way to
2418       make sure all assertions are on.
2419
2420       No assertion uses ASSERT_DEFAULT directly, and this assertion flag has
2421       no corresponding output prefix.
2422
2423       Turn on all assertions except ASSERT_EVENTS:
2424
2425         sub POE::Kernel::ASSERT_DEFAULT () { 1 }
2426         sub POE::Kernel::ASSERT_EVENTS  () { 0 }
2427         use POE::Kernel;
2428
2429       Prefix: (none)
2430
2431       Environment variable: POE_ASSERT_DEFAULT
2432
2433   ASSERT_EVENTS
2434       ASSERT_EVENTS mainly checks for attempts to dispatch events to sessions
2435       that don't exist.  This assertion can assist in the debugging of
2436       strange, silent cases where event handlers are not called.
2437
2438       Prefix: <ev>
2439
2440       Environment variable: POE_ASSERT_EVENTS
2441
2442   ASSERT_FILES
2443       ASSERT_FILES enables some run-time checks in POE's filehandle watchers
2444       and the code that manages them.
2445
2446       Prefix: <fh>
2447
2448       Environment variable: POE_ASSERT_FILES
2449
2450   ASSERT_RETVALS
2451       ASSERT_RETVALS upgrades failure codes from POE::Kernel's methods from
2452       advisory return values to fatal errors.  Most programmers don't check
2453       the values these methods return, so ASSERT_RETVALS is a quick way to
2454       validate one's assumption that all is correct.
2455
2456       Prefix: <rv>
2457
2458       Environment variable: POE_ASSERT_RETVALS
2459
2460   ASSERT_USAGE
2461       ASSERT_USAGE is the counterpoint to ASSERT_RETVALS.  It enables run-
2462       time checks that the parameters to POE::Kernel's methods are correct.
2463       It's a quick (but not foolproof) way to verify a program's use of POE.
2464
2465       Prefix: <us>
2466
2467       Environment variable: POE_ASSERT_USAGE
2468
2469   TRACE_DEFAULT
2470       TRACE_DEFAULT specifies the default value for traces that are not
2471       explicitly enabled or disabled.  This is a quick and reliable way to
2472       ensure your program generates copious output on the file named in
2473       TRACE_FILENAME or STDERR by default.
2474
2475       To enable all traces except a few noisier ones:
2476
2477         sub POE::Kernel::TRACE_DEFAULT () { 1 }
2478         sub POE::Kernel::TRACE_EVENTS  () { 0 }
2479         use POE::Kernel;
2480
2481       Prefix: (none)
2482
2483       Environment variable: POE_TRACE_DEFAULT
2484
2485   TRACE_DESTROY
2486       TRACE_DESTROY causes every POE::Session object to dump the contents of
2487       its $_[HEAP] when Perl destroys it.  This trace was added to help
2488       developers find memory leaks in their programs.
2489
2490       Prefix: A line that reads "----- Session $self Leak Check -----".
2491
2492       Environment variable: POE_TRACE_DESTROY
2493
2494   TRACE_EVENTS
2495       TRACE_EVENTS enables messages pertaining to POE's event queue's
2496       activities: when events are enqueued, dispatched or discarded, and
2497       more.  It's great for determining where events go and when.
2498       Understandably this is one of POE's more verbose traces.
2499
2500       Prefix: <ev>
2501
2502       Environment variable: POE_TRACE_EVENTS
2503
2504   TRACE_FILENAME
2505       TRACE_FILENAME specifies the name of a file where POE's tracing and
2506       assertion messages should go.  It's useful if you want the messages but
2507       have other plans for STDERR, which is where the messages go by default.
2508
2509       POE's tests use this so the trace and assertion code can be
2510       instrumented during testing without spewing all over the terminal.
2511
2512       Prefix: (none)
2513
2514       Environment variable: POE_TRACE_FILENAME
2515
2516   TRACE_FILES
2517       TRACE_FILES enables or disables traces in POE's filehandle watchers and
2518       the POE::Loop class that implements the lowest-level filehandle
2519       multiplexing.  This may be useful when tracking down strange behavior
2520       related to filehandles.
2521
2522       Prefix: <fh>
2523
2524       Environment variable: POE_TRACE_FILES
2525
2526   TRACE_REFCNT
2527       TRACE_REFCNT governs whether POE::Kernel will trace sessions' reference
2528       counts.  As discussed in "Session Lifespans", POE does a lot of
2529       reference counting, and the current state of a session's reference
2530       counts determines whether the session lives or dies.  It's common for
2531       developers to wonder why a session stops too early or remains active
2532       too long.  TRACE_REFCNT can help explain why.
2533
2534       Prefix: <rc>
2535
2536       Environment variable: POE_TRACE_REFCNT
2537
2538   TRACE_RETVALS
2539       TRACE_RETVALS can enable carping whenever a POE::Kernel method is about
2540       to fail.  It's a non-fatal but noisier form of ASSERT_RETVALS.
2541
2542       Prefix: <rv>
2543
2544       Environment variable: POE_TRACE_RETVALS
2545
2546   TRACE_SESSIONS
2547       TRACE_SESSIONS enables trace messages that pertain to session
2548       management.  Notice will be given when sessions are created or
2549       destroyed, and when the parent or child status of a session changes.
2550
2551       Prefix: <ss>
2552
2553       Environment variable: POE_TRACE_SESSIONS
2554
2555   TRACE_SIGNALS
2556       TRACE_SIGNALS turns on (or off) traces in POE's signal handling
2557       subsystem.  Signal dispatch is one of POE's more complex parts, and the
2558       trace messages may help application developers understand signal
2559       propagation and timing.
2560
2561       Prefix: <sg>
2562
2563       Environment variable: POE_TRACE_SIGNALS
2564
2565   USE_SIGCHLD
2566       Whether to use $SIG{CHLD} or to poll at an interval.
2567
2568       This flag is enabled by default on Perl >= 5.8.1 as it has support for
2569       "safe signals". Please see perlipc for the gory details.
2570
2571       You might want to disable this if you are running a version of Perl
2572       that is known to have bad signal handling, or if anything hijacks
2573       $SIG{CHLD}.  One module that is known to do this is Apache.
2574
2575       Enabling this flag will cause child reaping to happen almost
2576       immediately, as opposed to once per "CHILD_POLLING_INTERVAL".
2577
2578   CHILD_POLLING_INTERVAL
2579       The interval at which "wait" is called to determine if child processes
2580       need to be reaped and the "CHLD" signal emulated.
2581
2582       Defaults to 1 second.
2583
2584   USE_SIGNAL_PIPE
2585       The only safe way to handle signals is to implement a shared-nothing
2586       model.  POE builds a signal pipe that communicates between the signal
2587       handlers and the POE kernel loop in a safe and atomic manner.  The
2588       signal pipe is implemented with POE::Pipe::OneWay, using a "pipe"
2589       conduit on Unix.  Unfortunately, the signal pipe is not compatible with
2590       Windows and is not used on that platform.
2591
2592       If you wish to revert to the previous unsafe signal behaviour, you must
2593       set "USE_SIGNAL_PIPE" to 0, or the environment variable
2594       "POE_USE_SIGNAL_PIPE".
2595
2596   CATCH_EXCEPTIONS
2597       Whether or not POE should run event handler code in an eval { } and
2598       deliver the "DIE" signal on errors.
2599
2600       See "Exception Handling".
2601

ENVIRONMENT VARIABLES FOR TESTING

2603       POE's tests are lovely, dark and deep.  These environment variables
2604       allow testers to take roads less traveled.
2605
2606   POE_DANTIC
2607       Windows and Perls built for it tend to be poor at doing UNIXy things,
2608       although they do try.  POE being very UNIXy itself must skip a lot of
2609       Windows tests.  The POE_DANTIC environment variable will, when true,
2610       enable all these tests.  It's intended to be used from time to time to
2611       see whether Windows has improved in some area.
2612

SEE ALSO

2614       The SEE ALSO section in POE contains a table of contents covering the
2615       entire POE distribution.
2616

BUGS

2618       •   There is no mechanism in place to prevent external reference count
2619           names from clashing.
2620
2621       •   There is no mechanism to catch exceptions generated in another
2622           session.
2623

AUTHORS & COPYRIGHTS

2625       Please see POE for more information about authors and contributors.
2626
2627
2628
2629perl v5.32.1                      2021-01-27                    POE::Kernel(3)
Impressum