1POE::Kernel(3) User Contributed Perl Documentation POE::Kernel(3)
2
3
4
6 POE::Kernel - an event-based application kernel in Perl
7
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
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
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 TODO - discuss the POE::Kernel queue
255
256 Event Handlers
257
258 An event is handled by a function called an event handler, which is
259 some code that is designated to be called when a particular event is
260 dispatched. See "Event Handler Management" and POE::Session.
261
262 The term state is often used in place of event handler, especially when
263 treating sessions as event driven state machines.
264
265 Handlers are always called in scalar context for asynchronous events
266 (i.e. via post()). Synchronous events, invoked with call(), are
267 handled in the same context that call() was called.
268
269 Event handlers may not directly return references to objects in the
270 "POE" namespace. POE::Kernel will stringify these references to
271 prevent timing issues with certain objects' destruction. For example,
272 this error handler would cause errors because a deleted wheel would not
273 be destructed when one might think:
274
275 sub handle_error {
276 warn "Got an error";
277 delete $_[HEAP]{wheel};
278 }
279
280 The delete() call returns the deleted wheel member, which is then
281 returned implicitly by handle_error().
282
283 Using POE with Other Event Loops
284 POE::Kernel supports any number of event loops. Two are included in
285 the base distribution. Historically, POE included other loops but they
286 were moved into a separate distribution. You can find them and other
287 loops on the CPAN.
288
289 POE's public interfaces remain the same regardless of the event loop
290 being used. Since most graphical toolkits include some form of event
291 loop, back-end code should be portable to all of them.
292
293 POE's cooperation with other event loops lets POE be embedded into
294 other software. The common underlying event loop drives both the
295 application and POE. For example, by using POE::Loop::Glib, one can
296 embed POE into Vim, irssi, and so on. Application scripts can then
297 take advantage of POE::Component::Client::HTTP (and everything else) to
298 do large-scale work without blocking the rest of the program.
299
300 Because this is Perl, there are multiple ways to load an alternate
301 event loop. The simplest way is to load the event loop before loading
302 POE::Kernel.
303
304 use Gtk;
305 use POE;
306
307 Remember that POE loads POE::Kernel internally.
308
309 POE::Kernel examines the modules loaded before it and detects that Gtk
310 has been loaded. If POE::Loop::Gtk is available, POE loads and hooks
311 it into POE::Kernel automatically.
312
313 It's less mysterious to load the appropriate POE::Loop class directly.
314 Their names follow the format "POE::Loop::$loop_module_name", where
315 $loop_module_name is the name of the event loop module after each "::"
316 has been substituted with an underscore. It can be abbreviated using
317 POE's loader magic.
318
319 use POE qw( Loop::Event_Lib );
320
321 POE also recognizes XS loops, they reside in the
322 "POE::XS::Loop::$loop_module_name" namespace. Using them may give you
323 a performance improvement on your platform, as the eventloop are some
324 of the hottest code in the system. As always, benchmark your
325 application against various loops to see which one is best for your
326 workload and platform.
327
328 use POE qw( XS::Loop::EPoll );
329
330 Please don't load the loop modules directly, because POE will not have
331 a chance to initialize it's internal structures yet. Code written like
332 this will throw errors on startup. It might look like a bug in POE, but
333 it's just the way POE is designed.
334
335 use POE::Loop::IO_Poll;
336 use POE;
337
338 POE::Kernel also supports configuration directives on its own "use"
339 line. A loop explicitly specified this way will override the search
340 logic.
341
342 use POE::Kernel { loop => "Glib" };
343
344 Finally, one may specify the loop class by setting the POE::Loop or
345 POE::XS:Loop class name in the POE_EVENT_LOOP environment variable.
346 This mechanism was added for tests that need to specify the loop from a
347 distance.
348
349 BEGIN { $ENV{POE_EVENT_LOOP} = "POE::XS::Loop::Poll" }
350 use POE;
351
352 Of course this may also be set from your shell:
353
354 % export POE_EVENT_LOOP='POE::XS::Loop::Poll'
355 % make test
356
357 Many external event loops support their own callback mechanisms.
358 POE::Session's "postback()" and "callback()" methods return plain Perl
359 code references that will generate POE events when called.
360 Applications can pass these code references to event loops for use as
361 callbacks.
362
363 POE's distribution includes two event loop interfaces. CPAN holds
364 several more:
365
366 POE::Loop::Select (bundled)
367
368 By default POE uses its select() based loop to drive its event system.
369 This is perhaps the least efficient loop, but it is also the most
370 portable. POE optimizes for correctness above all.
371
372 POE::Loop::IO_Poll (bundled)
373
374 The IO::Poll event loop provides an alternative that theoretically
375 scales better than select().
376
377 POE::Loop::Event (separate distribution)
378
379 This event loop provides interoperability with other modules that use
380 Event. It may also provide a performance boost because Event is
381 written in a compiled language. Unfortunately, this makes Event less
382 portable than Perl's built-in select().
383
384 POE::Loop::Gtk (separate distribution)
385
386 This event loop allows programs to work under the Gtk graphical
387 toolkit.
388
389 POE::Loop::Tk (separate distribution)
390
391 This event loop allows programs to work under the Tk graphical toolkit.
392 Tk has some restrictions that require POE to behave oddly.
393
394 Tk's event loop will not run unless one or more widgets are created.
395 POE must therefore create such a widget before it can run. POE::Kernel
396 exports $poe_main_window so that the application developer may use the
397 widget (which is a MainWindow), since POE doesn't need it other than
398 for dispatching events.
399
400 Creating and using a different MainWindow often has an undesired
401 outcome.
402
403 POE::Loop::EV (separate distribution)
404
405 POE::Loop::EV allows POE-based programs to use the EV event library
406 with little or no change.
407
408 POE::Loop::Glib (separate distribution)
409
410 POE::Loop::Glib allows POE-based programs to use Glib with little or no
411 change. It also supports embedding POE-based programs into
412 applications that already use Glib. For example, we have heard that
413 POE has successfully embedded into vim, irssi and xchat via this loop.
414
415 POE::Loop::Kqueue (separate distribution)
416
417 POE::Loop::Kqueue allows POE-based programs to transparently use the
418 BSD kqueue event library on operating systems that support it.
419
420 POE::Loop::Prima (separate distribution)
421
422 POE::Loop::Prima allows POE-based programs to use Prima's event loop
423 with little or no change. It allows POE libraries to be used within
424 Prima applications.
425
426 POE::Loop::Wx (separate distribution)
427
428 POE::Loop::Wx allows POE-based programs to use Wx's event loop with
429 little or no change. It allows POE libraries to be used within Wx
430 applications, such as Padre.
431
432 POE::XS::Loop::EPoll (separate distribution)
433
434 POE::Loop::EPoll allows POE components to transparently use the EPoll
435 event library on operating systems that support it.
436
437 POE::XS::Loop::Poll (separate distribution)
438
439 POE::XS::Loop::Poll is a higher-performance C-based libpoll event loop.
440 It replaces some of POE's hot Perl code with C for better performance.
441
442 Other Event Loops (separate distributions)
443
444 POE may be extended to handle other event loops. Developers are
445 invited to work with us to support their favorite loops.
446
448 POE::Kernel encapsulates a lot of features. The documentation for each
449 set of features is grouped by purpose.
450
451 Kernel Management and Accessors
452 ID
453
454 ID() returns the kernel's unique identifier. Every POE::Kernel
455 instance is assigned a (hopefully) globally unique ID at birth.
456
457 % perl -wl -MPOE -e 'print $poe_kernel->ID'
458 poerbook.local-46c89ad800000e21
459
460 While the IDs are made globally unique by including hostname, time and
461 PID, they should be considered an opaque but printable string. That
462 is, your code should not depend on the current format.
463
464 run
465
466 run() runs POE::Kernel's event dispatcher. It will not return until
467 all sessions have ended. run() is a class method so a POE::Kernel
468 reference is not needed to start a program's execution.
469
470 use POE;
471 POE::Session->create( ... ); # one or more
472 POE::Kernel->run(); # set them all running
473 exit;
474
475 POE implements the Reactor pattern at its core. Events are dispatched
476 to functions and methods through callbacks. The code behind run()
477 waits for and dispatches events.
478
479 run() will not return until every session has ended. This includes
480 sessions that were created while run() was running.
481
482 POE::Kernel will print a strong message if a program creates sessions
483 but fails to call run(). Prior to this warning, we received tons of
484 bug reports along the lines of "my POE program isn't doing anything".
485 It turned out that people forgot to start an event dispatcher, so
486 events were never dispatched.
487
488 If the lack of a run() call is deliberate, perhaps because some other
489 event loop already has control, you can avoid the message by calling it
490 before creating a session. run() at that point will initialize POE and
491 return immediately. POE::Kernel will be satisfied that run() was
492 called, although POE will not have actually taken control of the event
493 loop.
494
495 use POE;
496 POE::Kernel->run(); # silence the warning
497 POE::Session->create( ... );
498 exit;
499
500 Note, however, that this varies from one event loop to another. If a
501 particular POE::Loop implementation doesn't support it, that's probably
502 a bug. Please file a bug report with the owner of the relevant
503 POE::Loop module.
504
505 run_one_timeslice
506
507 run_one_timeslice() dispatches any events that are due to be delivered.
508 These events include timers that are due, asynchronous messages that
509 need to be delivered, signals that require handling, and notifications
510 for files with pending I/O. Do not rely too much on event ordering.
511 run_one_timeslice() is defined by the underlying event loop, and its
512 timing may vary.
513
514 run() is implemented similar to
515
516 run_one_timeslice() while $session_count > 0;
517
518 run_one_timeslice() can be used to keep running POE::Kernel's
519 dispatcher while emulating blocking behavior. The pattern is
520 implemented with a flag that is set when some asynchronous event
521 occurs. A loop calls run_one_timeslice() until that flag is set. For
522 example:
523
524 my $done = 0;
525
526 sub handle_some_event {
527 $done = 1;
528 }
529
530 $kernel->run_one_timeslice() while not $done;
531
532 Do be careful. The above example will spin if POE::Kernel is done but
533 $done is never set. The loop will never be done, even though there's
534 nothing left that will set $done.
535
536 run_while SCALAR_REF
537
538 run_while() is an experimental version of run_one_timeslice() that will
539 only return when there are no more active sessions, or the value of the
540 referenced scalar becomes false.
541
542 Here's a version of the run_one_timeslice() example using run_while()
543 instead:
544
545 my $job_count = 3;
546
547 sub handle_some_event {
548 $job_count--;
549 }
550
551 $kernel->run_while(\$job_count);
552
553 has_forked
554
555 my $pid = fork();
556 die "Unable to fork" unless defined $pid;
557 unless( $pid ) {
558 $poe_kernel->has_forked;
559 }
560
561 Inform the kernel that it is now running in a new process. This allows
562 the kernel to reset some internal data to adjust to the new situation.
563
564 has_forked() must be called in the child process if you wish to run the
565 same kernel. However, if you want the child process to have new
566 kernel, you must call "stop" instead.
567
568 stop
569
570 stop() causes POE::Kernel->run() to return early. It does this by
571 emptying the event queue, freeing all used resources, and stopping
572 every active session. stop() is not meant to be used lightly. Proceed
573 with caution.
574
575 Caveats:
576
577 The session that calls stop() will not be fully DESTROYed until it
578 returns. Invoking an event handler in the session requires a reference
579 to that session, and weak references are prohibited in POE for backward
580 compatibility reasons, so it makes sense that the last session won't be
581 garbage collected right away.
582
583 Sessions are not notified about their destruction. If anything relies
584 on _stop being delivered, it will break and/or leak memory.
585
586 stop() is still considered experimental. It was added to improve
587 fork() support for POE::Wheel::Run. If it proves unfixably
588 problematic, it will be removed without much notice.
589
590 stop() is advanced magic. Programmers who think they need it are
591 invited to become familiar with its source.
592
593 See "Nested POE Kernel" in POE::Wheel::Run for an example of how to use
594 this facility.
595
596 Asynchronous Messages (FIFO Events)
597 Asynchronous messages are events that are dispatched in the order in
598 which they were enqueued (the first one in is the first one out,
599 otherwise known as first-in/first-out, or FIFO order). These methods
600 enqueue new messages for delivery. The act of enqueuing a message
601 keeps the sender alive at least until the message is delivered.
602
603 post DESTINATION, EVENT_NAME [, PARAMETER_LIST]
604
605 post() enqueues a message to be dispatched to a particular DESTINATION
606 session. The message will be handled by the code associated with
607 EVENT_NAME. If a PARAMETER_LIST is included, its values will also be
608 passed along.
609
610 POE::Session->create(
611 inline_states => {
612 _start => sub {
613 $_[KERNEL]->post( $_[SESSION], "event_name", 0 );
614 },
615 event_name => sub {
616 print "$_[ARG0]\n";
617 $_[KERNEL]->post( $_[SESSION], "event_name", $_[ARG0] + 1 );
618 },
619 }
620 );
621
622 post() returns a Boolean value indicating whether the message was
623 successfully enqueued. If post() returns false, $! is set to explain
624 the failure:
625
626 ESRCH ("No such process") - The DESTINATION session did not exist at
627 the time post() was called.
628
629 yield EVENT_NAME [, PARAMETER_LIST]
630
631 yield() is a shortcut for post() where the destination session is the
632 same as the sender. This example is equivalent to the one for post():
633
634 POE::Session->create(
635 inline_states => {
636 _start => sub {
637 $_[KERNEL]->yield( "event_name", 0 );
638 },
639 event_name => sub {
640 print "$_[ARG0]\n";
641 $_[KERNEL]->yield( "event_name", $_[ARG0] + 1 );
642 },
643 }
644 );
645
646 As with post(), yield() returns right away, and the enqueued EVENT_NAME
647 is dispatched later. This may be confusing if you're already familiar
648 with threading.
649
650 yield() should always succeed, so it does not return a meaningful
651 value.
652
653 Synchronous Messages
654 It is sometimes necessary for code to be invoked right away. For
655 example, some resources must be serviced right away, or they'll
656 faithfully continue reporting their readiness. These reports would
657 appear as a stream of duplicate events. Synchronous events can also
658 prevent data from going stale between the time an event is enqueued and
659 the time it's delivered.
660
661 Synchronous event handlers preempt POE's event queue, so they should
662 perform simple tasks of limited duration. Synchronous events that need
663 to do more than just service a resource should pass the resource's
664 information to an asynchronous handler. Otherwise synchronous
665 operations will occur out of order in relation to asynchronous events.
666 It's very easy to have race conditions or break causality this way, so
667 try to avoid it unless you're okay with the consequences.
668
669 POE provides these ways to call message handlers right away.
670
671 call DESTINATION, EVENT_NAME [, PARAMETER_LIST]
672
673 call()'s semantics are nearly identical to post()'s. call() invokes a
674 DESTINATION's handler associated with an EVENT_NAME. An optional
675 PARAMETER_LIST will be passed along to the message's handler. The
676 difference, however, is that the handler will be invoked immediately,
677 even before call() returns.
678
679 call() returns the value returned by the EVENT_NAME handler. It can do
680 this because the handler is invoked before call() returns. call() can
681 therefore be used as an accessor, although there are better ways to
682 accomplish simple accessor behavior.
683
684 POE::Session->create(
685 inline_states => {
686 _start => sub {
687 print "Got: ", $_[KERNEL]->call($_[SESSION], "do_now"), "\n";
688 },
689 do_now => sub {
690 return "some value";
691 }
692 }
693 );
694
695 The POE::Wheel classes uses call() to synchronously deliver I/O
696 notifications. This avoids a host of race conditions.
697
698 call() may fail in the same way and for the same reasons as post(). On
699 failure, $! is set to some nonzero value indicating why. Since call()
700 may return undef as a matter of course, it's recommended that $! be
701 checked for the error condition as well as the explanation.
702
703 ESRCH ("No such process") - The DESTINATION session did not exist at
704 the time post() was called.
705
706 Timer Events (Delayed Messages)
707 It's often useful to wait for a certain time or until a certain amount
708 of time has passed. POE supports this with events that are deferred
709 until either an absolute time ("alarms") or until a certain duration of
710 time has elapsed ("delays").
711
712 Timer interfaces are further divided into two groups. One group
713 identifies timers by the names of their associated events. Another
714 group identifies timers by a unique identifier returned by the timer
715 constructors. Technically, the two are both name-based, but the
716 "identifier-based" timers provide a second, more specific handle to
717 identify individual timers.
718
719 Timers may only be set up for the current session. This design was
720 modeled after alarm() and SIGALRM, which only affect the current UNIX
721 process. Each session has a separate namespace for timer names. Timer
722 methods called in one session cannot affect the timers in another. As
723 you may have noticed, quite a lot of POE's API is designed to prevent
724 sessions from interfering with each other.
725
726 The best way to simulate deferred inter-session messages is to send an
727 immediate message that causes the destination to set a timer. The
728 destination's timer then defers the action requested of it. This way
729 is preferred because the time spent communicating the request between
730 sessions may not be trivial, especially if the sessions are separated
731 by a network. The destination can determine how much time remains on
732 the requested timer and adjust its wait time accordingly.
733
734 Using Time::HiRes
735
736 POE::Kernel timers support sub-second accuracy, but don't expect too
737 much here. Perl is not the right language for realtime programming.
738
739 Subsecond accuracy is supported through the use of select() timeouts
740 and other event-loop features. For increased accuracy, POE::Kernel
741 uses Time::HiRes's time() internally, if it's available.
742
743 You can disable POE's use of Time::HiRes by defining a constant in the
744 POE::Kernel namespace. This must be done before POE::Kernel is loaded,
745 so that the compiler can use it.
746
747 BEGIN {
748 package POE::Kernel;
749 use constant USE_TIME_HIRES => 0;
750 }
751 use POE;
752
753 Or the old-fashioned (and more concise) "constant subroutine" method.
754 This doesn't need the "BEGIN{}" block since subroutine definitions are
755 done at compile time.
756
757 sub POE::Kernel::USE_TIME_HIRES () { 0 }
758 use POE;
759
760 Name-Based Timers
761
762 Name-based timers are identified by the event names used to set them.
763 It is possible for different sessions to use the same timer event
764 names, since each session is a separate compartment with its own timer
765 namespace. It is possible for a session to have multiple timers for a
766 given event, but results may be surprising. Be careful to use the
767 right timer methods.
768
769 The name-based timer methods are alarm(), alarm_add(), delay(), and
770 delay_add().
771
772 alarm EVENT_NAME [, EPOCH_TIME [, PARAMETER_LIST] ]
773
774 alarm() clears all existing timers in the current session with the same
775 EVENT_NAME. It then sets a new timer, named EVENT_NAME, that will fire
776 EVENT_NAME at the current session when EPOCH_TIME has been reached. An
777 optional PARAMETER_LIST may be passed along to the timer's handler.
778
779 Omitting the EPOCH_TIME and subsequent parameters causes alarm() to
780 clear the EVENT_NAME timers in the current session without setting a
781 new one.
782
783 EPOCH_TIME is the UNIX epoch time. You know, seconds since midnight,
784 1970-01-01. "Now" is whatever time() returns, either the built-in or
785 Time::HiRes version. POE will use Time::HiRes if it's available.
786
787 POE supports fractional seconds, but accuracy falls off steeply after
788 1/100 second. Mileage will vary depending on your CPU speed and your
789 OS time resolution.
790
791 Be sure to use Time::HiRes::time() rather than Perl's built-in time()
792 if sub-second accuracy matters at all. The built-in time() returns
793 floor(Time::HiRes::time()), which is nearly always some fraction of a
794 second in the past. For example the high-resolution time might be
795 1200941422.89996. At that same instant, time() would be 1200941422.
796 An alarm for time() + 0.5 would be 0.39996 seconds in the past, so it
797 would be dispatched immediately (if not sooner).
798
799 POE's event queue is time-ordered, so a timer due before time() will be
800 delivered ahead of other events but not before timers with even earlier
801 due times. Therefore an alarm() with an EPOCH_TIME before time() jumps
802 ahead of the queue.
803
804 All timers are implemented identically internally, regardless of how
805 they are set. alarm() will therefore blithely clear timers set by
806 other means.
807
808 POE::Session->create(
809 inline_states => {
810 _start => sub {
811 $_[KERNEL]->alarm( tick => time() + 1, 0 );
812 },
813 tick => sub {
814 print "tick $_[ARG0]\n";
815 $_[KERNEL]->alarm( tock => time() + 1, $_[ARG0] + 1 );
816 },
817 tock => sub {
818 print "tock $_[ARG0]\n";
819 $_[KERNEL]->alarm( tick => time() + 1, $_[ARG0] + 1 );
820 },
821 }
822 );
823
824 alarm() returns 0 on success or a true value on failure. Usually
825 EINVAL to signal an invalid parameter, such as an undefined EVENT_NAME.
826
827 alarm_add EVENT_NAME, EPOCH_TIME [, PARAMETER_LIST]
828
829 alarm_add() is used to add a new alarm timer named EVENT_NAME without
830 clearing existing timers. EPOCH_TIME is a required parameter.
831 Otherwise the semantics are identical to alarm().
832
833 A program may use alarm_add() without first using alarm().
834
835 POE::Session->create(
836 inline_states => {
837 _start => sub {
838 $_[KERNEL]->alarm_add( tick => time() + 1.0, 1_000_000 );
839 $_[KERNEL]->alarm_add( tick => time() + 1.5, 2_000_000 );
840 },
841 tick => sub {
842 print "tick $_[ARG0]\n";
843 $_[KERNEL]->alarm_add( tock => time() + 1, $_[ARG0] + 1 );
844 },
845 tock => sub {
846 print "tock $_[ARG0]\n";
847 $_[KERNEL]->alarm_add( tick => time() + 1, $_[ARG0] + 1 );
848 },
849 }
850 );
851
852 alarm_add() returns 0 on success or EINVAL if EVENT_NAME or EPOCH_TIME
853 is undefined.
854
855 delay EVENT_NAME [, DURATION_SECONDS [, PARAMETER_LIST] ]
856
857 delay() clears all existing timers in the current session with the same
858 EVENT_NAME. It then sets a new timer, named EVENT_NAME, that will fire
859 EVENT_NAME at the current session when DURATION_SECONDS have elapsed
860 from "now". An optional PARAMETER_LIST may be passed along to the
861 timer's handler.
862
863 Omitting the DURATION_SECONDS and subsequent parameters causes delay()
864 to clear the EVENT_NAME timers in the current session without setting a
865 new one.
866
867 DURATION_SECONDS may be or include fractional seconds. As with all of
868 POE's timers, accuracy falls off steeply after 1/100 second. Mileage
869 will vary depending on your CPU speed and your OS time resolution.
870
871 POE's event queue is time-ordered, so a timer due before time() will be
872 delivered ahead of other events but not before timers with even earlier
873 due times. Therefore a delay () with a zero or negative
874 DURATION_SECONDS jumps ahead of the queue.
875
876 delay() may be considered a shorthand form of alarm(), but there are
877 subtle differences in timing issues. This code is roughly equivalent
878 to the alarm() example.
879
880 POE::Session->create(
881 inline_states => {
882 _start => sub {
883 $_[KERNEL]->delay( tick => 1, 0 );
884 },
885 tick => sub {
886 print "tick $_[ARG0]\n";
887 $_[KERNEL]->delay( tock => 1, $_[ARG0] + 1 );
888 },
889 tock => sub {
890 print "tock $_[ARG0]\n";
891 $_[KERNEL]->delay( tick => 1, $_[ARG0] + 1 );
892 },
893 }
894 );
895
896 delay() returns 0 on success or a reason for failure: EINVAL if
897 EVENT_NAME is undefined.
898
899 delay_add EVENT_NAME, DURATION_SECONDS [, PARAMETER_LIST]
900
901 delay_add() is used to add a new delay timer named EVENT_NAME without
902 clearing existing timers. DURATION_SECONDS is a required parameter.
903 Otherwise the semantics are identical to delay().
904
905 A program may use delay_add() without first using delay().
906
907 POE::Session->create(
908 inline_states => {
909 _start => sub {
910 $_[KERNEL]->delay_add( tick => 1.0, 1_000_000 );
911 $_[KERNEL]->delay_add( tick => 1.5, 2_000_000 );
912 },
913 tick => sub {
914 print "tick $_[ARG0]\n";
915 $_[KERNEL]->delay_add( tock => 1, $_[ARG0] + 1 );
916 },
917 tock => sub {
918 print "tock $_[ARG0]\n";
919 $_[KERNEL]->delay_add( tick => 1, $_[ARG0] + 1 );
920 },
921 }
922 );
923
924 delay_add() returns 0 on success or EINVAL if EVENT_NAME or EPOCH_TIME
925 is undefined.
926
927 Identifier-Based Timers
928
929 A second way to manage timers is through identifiers. Setting an alarm
930 or delay with the "identifier" methods allows a program to manipulate
931 several timers with the same name in the same session. As covered in
932 alarm() and delay() however, it's possible to mix named and identified
933 timer calls, but the consequences may not always be expected.
934
935 alarm_set EVENT_NAME, EPOCH_TIME [, PARAMETER_LIST]
936
937 alarm_set() sets an alarm, returning a unique identifier that can be
938 used to adjust or remove the alarm later. Unlike alarm(), it does not
939 first clear existing timers with the same EVENT_NAME. Otherwise the
940 semantics are identical to alarm().
941
942 POE::Session->create(
943 inline_states => {
944 _start => sub {
945 $_[HEAP]{alarm_id} = $_[KERNEL]->alarm_set(
946 party => time() + 1999
947 );
948 $_[KERNEL]->delay(raid => 1);
949 },
950 raid => sub {
951 $_[KERNEL]->alarm_remove( delete $_[HEAP]{alarm_id} );
952 },
953 }
954 );
955
956 alarm_set() returns false if it fails and sets $! with the explanation.
957 $! will be EINVAL if EVENT_NAME or TIME is undefined.
958
959 alarm_adjust ALARM_ID, DELTA_SECONDS
960
961 alarm_adjust() adjusts an existing timer's due time by DELTA_SECONDS,
962 which may be positive or negative. It may even be zero, but that's not
963 as useful. On success, it returns the timer's new due time since the
964 start of the UNIX epoch.
965
966 It's possible to alarm_adjust() timers created by delay_set() as well
967 as alarm_set().
968
969 This example moves an alarm's due time ten seconds earlier.
970
971 use POSIX qw(strftime);
972
973 POE::Session->create(
974 inline_states => {
975 _start => sub {
976 $_[HEAP]{alarm_id} = $_[KERNEL]->alarm_set(
977 party => time() + 1999
978 );
979 $_[KERNEL]->delay(postpone => 1);
980 },
981 postpone => sub {
982 my $new_time = $_[KERNEL]->alarm_adjust(
983 $_[HEAP]{alarm_id}, -10
984 );
985 print(
986 "Now we're gonna party like it's ",
987 strftime("%F %T", gmtime($new_time)), "\n"
988 );
989 },
990 }
991 );
992
993 alarm_adjust() returns Boolean false if it fails, setting $! to the
994 reason why. $! may be EINVAL if ALARM_ID or DELTA_SECONDS are
995 undefined. It may be ESRCH if ALARM_ID no longer refers to a pending
996 timer. $! may also contain EPERM if ALARM_ID is valid but belongs to a
997 different session.
998
999 alarm_remove ALARM_ID
1000
1001 alarm_remove() removes the alarm identified by ALARM_ID. ALARM_ID
1002 comes from a previous alarm_set() or delay_set() call.
1003
1004 Upon success, alarm_remove() returns something true based on its
1005 context. In a list context, it returns three things: The removed
1006 alarm's event name, the UNIX time it was due to go off, and a reference
1007 to the PARAMETER_LIST (if any) assigned to the timer when it was
1008 created. If necessary, the timer can be re-set with this information.
1009
1010 POE::Session->create(
1011 inline_states => {
1012 _start => sub {
1013 $_[HEAP]{alarm_id} = $_[KERNEL]->alarm_set(
1014 party => time() + 1999
1015 );
1016 $_[KERNEL]->delay(raid => 1);
1017 },
1018 raid => sub {
1019 my ($name, $time, $param) = $_[KERNEL]->alarm_remove(
1020 $_[HEAP]{alarm_id}
1021 );
1022 print(
1023 "Removed alarm for event $name due at $time with @$param\n"
1024 );
1025
1026 # Or reset it, if you'd like. Possibly after modification.
1027 $_[KERNEL]->alarm_set($name, $time, @$param);
1028 },
1029 }
1030 );
1031
1032 In a scalar context, it returns a reference to a list of the three
1033 things above.
1034
1035 # Remove and reset an alarm.
1036 my $alarm_info = $_[KERNEL]->alarm_remove( $alarm_id );
1037 my $new_id = $_[KERNEL]->alarm_set(
1038 $alarm_info[0], $alarm_info[1], @{$alarm_info[2]}
1039 );
1040
1041 Upon failure, however, alarm_remove() returns a Boolean false value and
1042 sets $! with the reason why the call failed:
1043
1044 EINVAL ("Invalid argument") indicates a problem with one or more
1045 parameters, usually an undefined ALARM_ID.
1046
1047 ESRCH ("No such process") indicates that ALARM_ID did not refer to a
1048 pending alarm.
1049
1050 EPERM ("Operation not permitted"). A session cannot remove an alarm it
1051 does not own.
1052
1053 alarm_remove_all
1054
1055 alarm_remove_all() removes all the pending timers for the current
1056 session, regardless of creation method or type. This method takes no
1057 arguments. It returns information about the alarms that were removed,
1058 either as a list of alarms or a list reference depending whether
1059 alarm_remove_all() is called in scalar or list context.
1060
1061 Each removed alarm's information is identical to the format explained
1062 in alarm_remove().
1063
1064 sub some_event_handler {
1065 my @removed_alarms = $_[KERNEL]->alarm_remove_all();
1066 foreach my $alarm (@removed_alarms) {
1067 my ($name, $time, $param) = @$alarm;
1068 ...;
1069 }
1070 }
1071
1072 delay_set EVENT_NAME, DURATION_SECONDS [, PARAMETER_LIST]
1073
1074 delay_set() sets a timer for DURATION_SECONDS in the future. The timer
1075 will be dispatched to the code associated with EVENT_NAME in the
1076 current session. An optional PARAMETER_LIST will be passed through to
1077 the handler. It returns the same sort of things that alarm_set() does.
1078
1079 POE::Session->create(
1080 inline_states => {
1081 _start => sub {
1082 $_[KERNEL]->delay_set("later", 5, "hello", "world");
1083 },
1084 later => sub {
1085 print "@_[ARG0..#$_]\n";
1086 }
1087 }
1088 );
1089
1090 delay_adjust EVENT_NAME, SECONDS_FROM_NOW
1091
1092 delay_adjust() changes a timer's due time to be SECONDS_FROM_NOW. It's
1093 useful for refreshing watchdog- or timeout-style timers. On success it
1094 returns the new absolute UNIX time the timer will be due.
1095
1096 It's possible for delay_adjust() to adjust timers created by
1097 alarm_set() as well as delay_set().
1098
1099 use POSIX qw(strftime);
1100
1101 POE::Session->create(
1102 inline_states => {
1103 # Setup.
1104 # ... omitted.
1105
1106 got_input => sub {
1107 my $new_time = $_[KERNEL]->delay_adjust(
1108 $_[HEAP]{input_timeout}, 60
1109 );
1110 print(
1111 "Refreshed the input timeout. Next may occur at ",
1112 strftime("%F %T", gmtime($new_time)), "\n"
1113 );
1114 },
1115 }
1116 );
1117
1118 On failure it returns Boolean false and sets $! to a reason for the
1119 failure. See the explanation of $! for alarm_adjust().
1120
1121 delay_remove is not needed
1122
1123 There is no delay_remove(). Timers are all identical internally, so
1124 alarm_remove() will work with timer IDs returned by delay_set().
1125
1126 delay_remove_all is not needed
1127
1128 There is no delay_remove_all(). Timers are all identical internally,
1129 so alarm_remove_all() clears them all regardless how they were created.
1130
1131 Session Identifiers (IDs and Aliases)
1132 A session may be referred to by its object references (either blessed
1133 or stringified), a session ID, or one or more symbolic names we call
1134 aliases.
1135
1136 Every session is represented by an object, so session references are
1137 fairly straightforward. POE::Kernel may reference these objects. For
1138 instance, post() may use $_[SENDER] as a destination:
1139
1140 POE::Session->create(
1141 inline_states => {
1142 _start => sub { $_[KERNEL]->alias_set("echoer") },
1143 ping => sub {
1144 $_[KERNEL]->post( $_[SENDER], "pong", @_[ARG0..$#_] );
1145 }
1146 }
1147 );
1148
1149 POE also recognized stringified Session objects for convenience and as
1150 a form of weak reference. Here $_[SENDER] is wrapped in quotes to
1151 stringify it:
1152
1153 POE::Session->create(
1154 inline_states => {
1155 _start => sub { $_[KERNEL]->alias_set("echoer") },
1156 ping => sub {
1157 $_[KERNEL]->post( "$_[SENDER]", "pong", @_[ARG0..$#_] );
1158 }
1159 }
1160 );
1161
1162 Every session is assigned a unique ID at creation time. No two active
1163 sessions will have the same ID, but IDs may be reused over time. The
1164 combination of a kernel ID and a session ID should be sufficient as a
1165 global unique identifier.
1166
1167 POE::Session->create(
1168 inline_states => {
1169 _start => sub { $_[KERNEL]->alias_set("echoer") },
1170 ping => sub {
1171 $_[KERNEL]->delay(
1172 pong_later => rand(5), $_[SENDER]->ID, @_[ARG0..$#_]
1173 );
1174 },
1175 pong_later => sub {
1176 $_[KERNEL]->post( $_[ARG0], "pong", @_[ARG1..$#_] );
1177 }
1178 }
1179 );
1180
1181 Kernels also maintain a global session namespace or dictionary from
1182 which may be used to map a symbolic aliases to a session. Once an alias
1183 is mapping has been created, that alias may be used to refer to the
1184 session wherever a session may be specified.
1185
1186 In the previous examples, each echoer service has set an "echoer"
1187 alias. Another session can post a ping request to the echoer session
1188 by using that alias rather than a session object or ID. For example:
1189
1190 POE::Session->create(
1191 inline_states => {
1192 _start => sub { $_[KERNEL]->post(echoer => ping => "whee!" ) },
1193 pong => sub { print "@_[ARG0..$#_]\n" }
1194 }
1195 );
1196
1197 A session with an alias will not stop until all other activity has
1198 stopped. Aliases are treated as a kind of event watcher. Events come
1199 from active sessions. Aliases therefore become useless when there are
1200 no active sessions left. Rather than leaving the program running in a
1201 "zombie" state, POE detects this deadlock condition and triggers a
1202 cleanup. See "Signal Classes" for more information.
1203
1204 alias_set ALIAS
1205
1206 alias_set() maps an ALIAS in POE::Kernel's dictionary to the current
1207 session. The ALIAS may then be used nearly everywhere a session
1208 reference, stringified reference, or ID is expected.
1209
1210 Sessions may have more than one alias. Each alias must be defined in a
1211 separate alias_set() call. A single alias may not refer to more than
1212 one session.
1213
1214 Multiple alias examples are above.
1215
1216 alias_set() returns 0 on success, or a nonzero failure indicator:
1217 EEXIST ("File exists") indicates that the alias is already assigned to
1218 to a different session.
1219
1220 alias_remove ALIAS
1221
1222 alias_remove() removes an ALIAS for the current session from
1223 POE::Kernel's dictionary. The ALIAS will no longer refer to the
1224 current session. This does not negatively affect events already posted
1225 to POE's queue. Alias resolution occurs at post() time, not at
1226 delivery time.
1227
1228 POE::Session->create(
1229 inline_states => {
1230 _start => sub {
1231 $_[KERNEL]->alias_set("short_window");
1232 $_[KERNEL]->delay(close_window => 1);
1233 },
1234 close_window => {
1235 $_[KERNEL]->alias_remove("short_window");
1236 }
1237 }
1238 );
1239
1240 alias_remove() returns 0 on success or a nonzero failure code: ESRCH
1241 ("No such process") indicates that the ALIAS is not currently in
1242 POE::Kernel's dictionary. EPERM ("Operation not permitted") means that
1243 the current session may not remove the ALIAS because it is in use by
1244 some other session.
1245
1246 alias_resolve ALIAS
1247
1248 alias_resolve() returns a session reference corresponding to a given
1249 ALIAS. Actually, the ALIAS may be a stringified session reference, a
1250 session ID, or an alias previously registered by alias_set().
1251
1252 One use for alias_resolve() is to detect whether another session has
1253 gone away:
1254
1255 unless (defined $_[KERNEL]->alias_resolve("Elvis")) {
1256 print "Elvis has left the building.\n";
1257 }
1258
1259 As previously mentioned, alias_resolve() returns a session reference or
1260 undef on failure. Failure also sets $! to ESRCH ("No such process")
1261 when the ALIAS is not currently in POE::Kernel's.
1262
1263 alias_list [SESSION_REFERENCE]
1264
1265 alias_list() returns a list of aliases associated with a specific
1266 SESSION, or with the current session if SESSION is omitted.
1267 alias_list() returns an empty list if the requested SESSION has no
1268 aliases.
1269
1270 SESSION may be a session reference (blessed or stringified), a session
1271 ID, or a session alias.
1272
1273 POE::Session->create(
1274 inline_states => {
1275 $_[KERNEL]->alias_set("mi");
1276 print(
1277 "The names I call myself: ",
1278 join(", ", $_[KERNEL]->alias_resolve()),
1279 "\n"
1280 );
1281 }
1282 );
1283
1284 ID_id_to_session SESSION_ID
1285
1286 ID_id_to_session() translates a session ID into a session reference.
1287 It's a special-purpose subset of alias_resolve(), so it's a little
1288 faster and somewhat less flexible.
1289
1290 unless (defined $_[KERNEL]->ID_id_to_session($session_id)) {
1291 print "Session $session_id doesn't exist.\n";
1292 }
1293
1294 ID_id_to_session() returns undef if a lookup failed. $! will be set to
1295 ESRCH ("No such process").
1296
1297 ID_session_to_id SESSION_REFERENCE
1298
1299 ID_session_to_id() converts a blessed or stringified SESSION_REFERENCE
1300 into a session ID. It's more practical for stringified references, as
1301 programs can call the POE::Session ID() method on the blessed ones.
1302 These statements are equivalent:
1303
1304 $id = $_[SENDER]->ID();
1305 $id = $_[KERNEL]->ID_session_to_id($_[SENDER]);
1306 $id = $_[KERNEL]->ID_session_to_id("$_[SENDER]");
1307
1308 As with other POE::Kernel lookup methods, ID_session_to_id() returns
1309 undef on failure, setting $! to ESRCH ("No such process").
1310
1311 I/O Watchers (Selects)
1312 No event system would be complete without the ability to asynchronously
1313 watch for I/O events. POE::Kernel implements the lowest level
1314 watchers, which are called "selects" because they were historically
1315 implemented using Perl's built-in select(2) function.
1316
1317 Applications handle I/O readiness events by performing some activity on
1318 the underlying filehandle. Read-readiness might be handled by reading
1319 from the handle. Write-readiness by writing to it.
1320
1321 All I/O watcher events include two parameters. "ARG0" contains the
1322 handle that is ready for work. "ARG1" contains an integer describing
1323 what's ready.
1324
1325 sub handle_io {
1326 my ($handle, $mode) = @_[ARG0, ARG1];
1327 print "File $handle is ready for ";
1328 if ($mode == 0) {
1329 print "reading";
1330 }
1331 elsif ($mode == 1) {
1332 print "writing";
1333 }
1334 elsif ($mode == 2) {
1335 print "out-of-band reading";
1336 }
1337 else {
1338 die "unknown mode $mode";
1339 }
1340 print "\n";
1341 # ... do something here
1342 }
1343
1344 The remaining parameters, @_[ARG2..$%_], contain additional parameters
1345 that were passed to the POE::Kernel method that created the watcher.
1346
1347 POE::Kernel conditions filehandles to be 8-bit clean and non-blocking.
1348 Programs that need them conditioned differently should set them up
1349 after starting POE I/O watchers.
1350
1351 I/O watchers will prevent sessions from stopping.
1352
1353 select_read FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]
1354
1355 select_read() starts or stops the current session from watching for
1356 incoming data on a given FILE_HANDLE. The watcher is started if
1357 EVENT_NAME is specified, or stopped if it's not.
1358 ADDITIONAL_PARAMETERS, if specified, will be passed to the EVENT_NAME
1359 handler as @_[ARG2..$#_].
1360
1361 POE::Session->create(
1362 inline_states => {
1363 _start => sub {
1364 $_[HEAP]{socket} = IO::Socket::INET->new(
1365 PeerAddr => "localhost",
1366 PeerPort => 25,
1367 );
1368 $_[KERNEL]->select_read( $_[HEAP]{socket}, "got_input" );
1369 $_[KERNEL]->delay(timed_out => 1);
1370 },
1371 got_input => sub {
1372 my $socket = $_[ARG0];
1373 while (sysread($socket, my $buf = "", 8192)) {
1374 print $buf;
1375 }
1376 },
1377 timed_out => sub {
1378 $_[KERNEL]->select_read( delete $_[HEAP]{socket} );
1379 },
1380 }
1381 );
1382
1383 select_read() does not return anything significant.
1384
1385 select_write FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]
1386
1387 select_write() follows the same semantics as select_read(), but it
1388 starts or stops a watcher that looks for write-readiness. That is,
1389 when EVENT_NAME is delivered, it means that FILE_HANDLE is ready to be
1390 written to.
1391
1392 TODO - Practical example here.
1393
1394 select_write() does not return anything significant.
1395
1396 select_expedite FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]
1397
1398 select_expedite() does the same sort of thing as select_read() and
1399 select_write(), but it watches a FILE_HANDLE for out-of-band data ready
1400 to be input from a FILE_HANDLE. Hardly anybody uses this, but it
1401 exists for completeness' sake.
1402
1403 An EVENT_NAME event will be delivered whenever the FILE_HANDLE can be
1404 read from out-of-band. Out-of-band data is considered "expedited"
1405 because it is often ahead of a socket's normal data.
1406
1407 select_expedite() does not return anything significant.
1408
1409 TODO - Practical example here.
1410
1411 select_pause_read FILE_HANDLE
1412
1413 select_pause_read() is a lightweight way to pause a FILE_HANDLE input
1414 watcher without performing all the bookkeeping of a select_read().
1415 It's used with select_resume_read() to implement input flow control.
1416
1417 Input that occurs on FILE_HANDLE will backlog in the operating system
1418 buffers until select_resume_read() is called.
1419
1420 A side effect of bypassing the select_read() bookkeeping is that a
1421 paused FILE_HANDLE will not prematurely stop the current session.
1422
1423 select_pause_read() does not return anything significant.
1424
1425 TODO - Practical example here.
1426
1427 select_resume_read FILE_HANDLE
1428
1429 select_resume_read() resumes a FILE_HANDLE input watcher that was
1430 previously paused by select_pause_read(). See select_pause_read() for
1431 more discussion on lightweight input flow control.
1432
1433 Data backlogged in the operating system due to a select_pause_read()
1434 call will become available after select_resume_read() is called.
1435
1436 select_resume_read() does not return anything significant.
1437
1438 TODO - Practical example here.
1439
1440 select_pause_write FILE_HANDLE
1441
1442 select_pause_write() pauses a FILE_HANDLE output watcher the same way
1443 select_pause_read() does for input. Please see select_pause_read() for
1444 further discussion.
1445
1446 TODO - Practical example here.
1447
1448 select_resume_write FILE_HANDLE
1449
1450 select_resume_write() resumes a FILE_HANDLE output watcher the same way
1451 that select_resume_read() does for input. See select_resume_read() for
1452 further discussion.
1453
1454 TODO - Practical example here.
1455
1456 select FILE_HANDLE [, EV_READ [, EV_WRITE [, EV_EXPEDITE [, ARGS] ] ] ]
1457
1458 POE::Kernel's select() method sets or clears a FILE_HANDLE's read,
1459 write and expedite watchers at once. It's a little more expensive than
1460 calling select_read(), select_write() and select_expedite() manually,
1461 but it's significantly more convenient.
1462
1463 Defined event names enable their corresponding watchers, and undefined
1464 event names disable them. This turns off all the watchers for a
1465 FILE_HANDLE:
1466
1467 sub stop_io {
1468 $_[KERNEL]->select( $_[HEAP]{file_handle} );
1469 }
1470
1471 This statement:
1472
1473 $_[KERNEL]->select( $file_handle, undef, "write_event", undef, @stuff );
1474
1475 is equivalent to:
1476
1477 $_[KERNEL]->select_read( $file_handle );
1478 $_[KERNEL]->select_write( $file_handle, "write_event", @stuff );
1479 $_[KERNEL]->select_expedite( $file_handle );
1480
1481 POE::Kernel's select() should not be confused with Perl's built-in
1482 select() function.
1483
1484 As with the other I/O watcher methods, select() does not return a
1485 meaningful value.
1486
1487 Session Management
1488 Sessions are dynamic. They may be created and destroyed during a
1489 program's lifespan. When a session is created, it becomes the "child"
1490 of the current session. The creator -- the current session -- becomes
1491 its "parent" session. This is loosely modeled after UNIX processes.
1492
1493 The most common session management is done by creating new sessions and
1494 allowing them to eventually stop.
1495
1496 Every session has a parent, even the very first session created.
1497 Sessions without obvious parents are children of the program's
1498 POE::Kernel instance.
1499
1500 Child sessions will keep their parents active. See Session Lifespans
1501 for more about why sessions stay alive.
1502
1503 The parent/child relationship tree also governs the way many signals
1504 are dispatched. See "Signal Watchers" for more information on that.
1505
1506 Session Management Events (_start, _stop, _parent, _child)
1507
1508 POE::Kernel provides four session management events: _start, _stop,
1509 _parent and _child. They are invoked synchronously whenever a session
1510 is newly created or just about to be destroyed.
1511
1512 _start
1513 _start should be familiar by now. POE dispatches the _start event to
1514 initialize a session after it has been registered under POE::Kernel.
1515 What is not readily apparent, however, is that it is invoked before
1516 the POE::Session constructor returns.
1517
1518 Within the _start handler, the event's sender is the session that
1519 created the new session. Otherwise known as the new session's
1520 parent. Sessions created before POE::Kernel->run() is called will be
1521 descendents of the program's POE::Kernel singleton.
1522
1523 The _start handler's return value is passed to the parent session in
1524 a _child event, along with the notification that the parent's new
1525 child was created successfully. See the discussion of _child for
1526 more details.
1527
1528 POE::Session->create(
1529 inline_states => { _start=> \&_start },
1530 args => [ $some, $args ]
1531 );
1532
1533 sub _start {
1534 my ( $some, $args ) = @_[ ARG0, ARG1 ];
1535 # ....
1536 }
1537
1538 _stop
1539 _stop is a little more mysterious. POE calls a _stop handler when a
1540 session is irrevocably about to be destroyed. Part of session
1541 destruction is the forcible reclamation of its resources (events,
1542 timers, message events, etc.) so it's not possible to post() a
1543 message from _stop's handler. A program is free to try, but the
1544 event will be destroyed before it has a chance to be dispatched.
1545
1546 the _stop handler's return value is passed to the parent's _child
1547 event. See _child for more details.
1548
1549 _stop is usually invoked when a session has no further reason to
1550 live, although signals may cause them to stop sooner.
1551
1552 The corresponding _child handler is invoked synchronously just after
1553 _stop returns.
1554
1555 _parent
1556 _parent is used to notify a child session when its parent has
1557 changed. This usually happens when a session is first created. It
1558 can also happen when a child session is detached from its parent. See
1559 detach_child and "detach_myself".
1560
1561 _parent's ARG0 contains the session's previous parent, and ARG1
1562 contains its new parent.
1563
1564 sub _parent {
1565 my ( $old_parent, $new_parent ) = @_[ ARG0, ARG1 ];
1566 print(
1567 "Session ", $_[SESSION]->ID,
1568 " parent changed from session ", $old_parent->ID,
1569 " to session ", $new_parent->ID,
1570 "\n"
1571 );
1572 }
1573
1574 _child
1575 _child notifies one session when a child session has been created,
1576 destroyed, or reassigned to or from another parent. It's usually
1577 dispatched when sessions are created or destroyed. It can also
1578 happen when a session is detached from its parent.
1579
1580 _child includes some information in the "arguments" portion of @_.
1581 Typically ARG0, ARG1 and ARG2, but these may be overridden by a
1582 different POE::Session class:
1583
1584 ARG0 contains a string describing what has happened to the child.
1585 The string may be 'create' (the child session has been created),
1586 'gain' (the child has been given by another session), or 'lose' (the
1587 child session has stopped or been given away).
1588
1589 In all cases, ARG1 contains a reference to the child session.
1590
1591 In the 'create' case, ARG2 holds the value returned by the child
1592 session's _start handler. Likewise, ARG2 holds the _stop handler's
1593 return value for the 'lose' case.
1594
1595 sub _child {
1596 my( $reason, $child ) = @_[ ARG0, ARG1 ];
1597 if( $reason eq 'create' ) {
1598 my $retval = $_[ ARG2 ];
1599 }
1600 # ...
1601 }
1602
1603 The events are delivered in specific orders.
1604
1605 When a new session is created:
1606
1607 1. The session's constructor is called.
1608
1609 2. The session is put into play. That is, POE::Kernel enters the
1610 session into its bookkeeping.
1611
1612 3. The new session receives _start.
1613
1614 4. The parent session receives _child ('create'), the new session
1615 reference, and the new session's _start's return value.
1616
1617 5. The session's constructor returns.
1618
1619 When an old session stops:
1620
1621 1. If the session has children of its own, they are given to the
1622 session's parent. This triggers one or more _child ('gain') events
1623 in the parent, and a _parent in each child.
1624
1625 2. Once divested of its children, the stopping session receives a
1626 _stop event.
1627
1628 3. The stopped session's parent receives a _child ('lose') event with
1629 the departing child's reference and _stop handler's return value.
1630
1631 4. The stopped session is removed from play, as are all its remaining
1632 resources.
1633
1634 5. The parent session is checked for idleness. If so, garbage
1635 collection will commence on it, and it too will be stopped
1636
1637 When a session is detached from its parent:
1638
1639 1. The parent session of the session being detached is notified with a
1640 _child ('lose') event. The _stop handler's return value is undef
1641 since the child is not actually stopping.
1642
1643 2. The detached session is notified with a _parent event that its new
1644 parent is POE::Kernel itself.
1645
1646 3. POE::Kernel's bookkeeping data is adjusted to reflect the change of
1647 parentage.
1648
1649 4. The old parent session is checked for idleness. If so, garbage
1650 collection will commence on it, and it too will be stopped
1651
1652 Session Management Methods
1653
1654 These methods allow sessions to be detached from their parents in the
1655 rare cases where the parent/child relationship gets in the way.
1656
1657 detach_child CHILD_SESSION
1658
1659 detach_child() detaches a particular CHILD_SESSION from the current
1660 session. On success, the CHILD_SESSION will become a child of the
1661 POE::Kernel instance, and detach_child() will return true. On failure
1662 however, detach_child() returns false and sets $! to explain the nature
1663 of the failure:
1664
1665 ESRCH ("No such process").
1666 The CHILD_SESSION is not a valid session.
1667
1668 EPERM ("Operation not permitted").
1669 The CHILD_SESSION exists, but it is not a child of the current
1670 session.
1671
1672 detach_child() will generate "_parent" and/or "_child" events to the
1673 appropriate sessions. See "Session Management Events" for a detailed
1674 explanation of these events. See above for the order the events are
1675 generated.
1676
1677 detach_myself
1678
1679 detach_myself() detaches the current session from its current parent.
1680 The new parent will be the running POE::Kernel instance. It returns
1681 true on success. On failure it returns false and sets $! to explain
1682 the nature of the failure:
1683
1684 EPERM ("Operation not permitted").
1685 The current session is already a child of POE::Kernel, so it may
1686 not be detached.
1687
1688 detach_child() will generate "_parent" and/or "_child" events to the
1689 appropriate sessions. See "Session Management Events" for a detailed
1690 explanation of these events. See above for the order the events are
1691 generated.
1692
1693 Signals
1694 POE::Kernel provides methods through which a program can register
1695 interest in signals that come along, can deliver its own signals
1696 without resorting to system calls, and can indicate that signals have
1697 been handled so that default behaviors are not necessary.
1698
1699 Signals are action at a distance by nature, and their implementation
1700 requires widespread synchronization between sessions (and reentrancy in
1701 the dispatcher, but that's an implementation detail). Perfecting the
1702 semantics has proven difficult, but POE tries to do the Right Thing
1703 whenever possible.
1704
1705 POE does not register %SIG handlers for signals until sig() is called
1706 to watch for them. Therefore a signal's default behavior occurs for
1707 unhandled signals. That is, SIGINT will gracelessly stop a program,
1708 SIGWINCH will do nothing, SIGTSTP will pause a program, and so on.
1709
1710 Signal Classes
1711
1712 There are three signal classes. Each class defines a default behavior
1713 for the signal and whether the default can be overridden. They are:
1714
1715 Benign, advisory, or informative signals
1716
1717 These are three names for the same signal class. Signals in this class
1718 notify a session of an event but do not terminate the session if they
1719 are not handled.
1720
1721 It is possible for an application to create its own benign signals.
1722 See "signal" below.
1723
1724 Terminal signals
1725
1726 Terminal signals will kill sessions if they are not handled by a
1727 "sig_handled"() call. The OS signals that usually kill or dump a
1728 process are considered terminal in POE, but they never trigger a
1729 coredump. These are: HUP, INT, QUIT and TERM.
1730
1731 There are two terminal signals created by and used within POE:
1732
1733 DIE "DIE" notifies sessions that a Perl exception has occurred. See
1734 "Exception Handling" for details.
1735
1736 IDLE
1737 The "IDLE" signal is used to notify leftover sessions that a
1738 program has run out of things to do.
1739
1740 Nonmaskable signals
1741
1742 Nonmaskable signals are terminal regardless whether sig_handled() is
1743 called. The term comes from "NMI", the non-maskable CPU interrupt
1744 usually generated by an unrecoverable hardware exception.
1745
1746 Sessions that receive a non-maskable signal will unavoidably stop. POE
1747 implements two non-maskable signals:
1748
1749 ZOMBIE
1750 This non-maskable signal is fired if a program has received an
1751 "IDLE" signal but neither restarted nor exited. The program has
1752 become a zombie (that is, it's neither dead nor alive, and only
1753 exists to consume braaaains ...er... memory). The "ZOMBIE" signal
1754 acts like a cricket bat to the head, bringing the zombie down, for
1755 good.
1756
1757 UIDESTROY
1758 This non-maskable signal indicates that a program's user interface
1759 has been closed, and the program should take the user's hint and
1760 buzz off as well. It's usually generated when a particular GUI
1761 widget is closed.
1762
1763 Common Signal Dispatching
1764
1765 Most signals are not dispatched to a single session. POE's session
1766 lineage (parents and children) form a sort of family tree. When a
1767 signal is sent to a session, it first passes through any children (and
1768 grandchildren, and so on) that are also interested in the signal.
1769
1770 In the case of terminal signals, if any of the sessions a signal passes
1771 through calls "sig_handled"(), then the signal is considered taken care
1772 of. However if none of them do, then the entire session tree rooted at
1773 the destination session is terminated. For example, consider this tree
1774 of sessions:
1775
1776 POE::Kernel
1777 Session 2
1778 Session 4
1779 Session 5
1780 Session 3
1781 Session 6
1782 Session 7
1783
1784 POE::Kernel is the parent of sessions 2 and 3. Session 2 is the parent
1785 of sessions 4 and 5. And session 3 is the parent of 6 and 7.
1786
1787 A signal sent to Session 2 may also be dispatched to session 4 and 5
1788 because they are 2's children. Sessions 4 and 5 will only receive the
1789 signal if they have registered the appropriate watcher. If the signal
1790 is terminal, and none of the signal watchers in sessions 2, 4 and 5
1791 called "sig_handled()", all 3 sessions will be terminated.
1792
1793 The program's POE::Kernel instance is considered to be a session for
1794 the purpose of signal dispatch. So any signal sent to POE::Kernel will
1795 propagate through every interested session in the entire program. This
1796 is in fact how OS signals are handled: A global signal handler is
1797 registered to forward the signal to POE::Kernel.
1798
1799 Signal Semantics
1800
1801 All signals come with the signal name in ARG0. The signal name is as
1802 it appears in %SIG, with one exception: Child process signals are
1803 always "CHLD" even if the current operating system recognizes them as
1804 "CLD".
1805
1806 Certain signals have special semantics:
1807
1808 SIGCHLD
1809
1810 SIGCLD
1811
1812 Both "SIGCHLD" and "SIGCLD" indicate that a child process has exited or
1813 been terminated by some signal. The actual signal name varies between
1814 operating systems, but POE uses "CHLD" regardless.
1815
1816 Interest in "SIGCHLD" is registered using the "sig_child" method. The
1817 "sig"() method also works, but it's not as nice.
1818
1819 The "SIGCHLD" event includes three parameters:
1820
1821 ARG0
1822 "ARG0" contains the string 'CHLD' (even if the OS calls it SIGCLD,
1823 SIGMONKEY, or something else).
1824
1825 ARG1
1826 "ARG1" contains the process ID of the finished child process.
1827
1828 ARG2
1829 And "ARG2" holds the value of $? for the finished process.
1830
1831 Example:
1832
1833 sub sig_CHLD {
1834 my( $name, $PID, $exit_val ) = @_[ ARG0, ARG1, ARG2 ];
1835 # ...
1836 }
1837
1838 By default, SIGCHLD is not handled by registering a %SIG handler.
1839 Rather, waitpid() is called periodically to test for child process
1840 exits. See the experimental USE_SIGCHLD option if you would prefer
1841 child processes to be reaped in a more timely fashion.
1842
1843 SIGPIPE
1844
1845 SIGPIPE is rarely used since POE provides events that do the same
1846 thing. Nevertheless SIGPIPE is supported if you need it. Unlike most
1847 events, however, SIGPIPE is dispatched directly to the active session
1848 when it's caught. Barring race conditions, the active session should
1849 be the one that caused the OS to send the signal in the first place.
1850
1851 The SIGPIPE signal will still propagate to child sessions.
1852
1853 ARG0 is "PIPE". There is no other information associated with this
1854 signal.
1855
1856 SIGWINCH
1857
1858 Window resizes can generate a large number of signals very quickly.
1859 This may not be a problem when using perl 5.8.0 or later, but earlier
1860 versions may not take kindly to such abuse. You have been warned.
1861
1862 ARG0 is "WINCH". There is no other information associated with this
1863 signal.
1864
1865 Exception Handling
1866
1867 POE::Kernel provides only one form of exception handling: the "DIE"
1868 signal.
1869
1870 When exception handling is enabled (the default), POE::Kernel wraps
1871 state invocation in "eval{}". If the event handler raises an
1872 exception, generally with "die", POE::Kernel will dispatch a "DIE"
1873 signal to the event's destination session.
1874
1875 "ARG0" is the signal name, "DIE".
1876
1877 "ARG1" is a hashref describing the exception:
1878
1879 error_str
1880 The text of the exception. In other words, $@.
1881
1882 dest_session
1883 Session object of the state that the raised the exception. In
1884 other words, $_[SESSION] in the function that died.
1885
1886 event
1887 Name of the event that died.
1888
1889 source_session
1890 Session object that sent the original event. That is, $_[SENDER]
1891 in the function that died.
1892
1893 from_state
1894 State from which the original event was sent. That is,
1895 $_[CALLER_STATE] in the function that died.
1896
1897 file
1898 Name of the file the event was sent from. That is, $_[CALLER_FILE]
1899 in the function that died.
1900
1901 line
1902 Line number the event was sent from. That is, $_[CALLER_LINE] in
1903 the function that died.
1904
1905 Note that the preceding discussion assumes you are using POE::Session's
1906 call semantics.
1907
1908 Note that the "DIE" signal is sent to the session that raised the
1909 exception, not the session that sent the event that caused the
1910 exception to be raised.
1911
1912 sub _start {
1913 $poe_kernel->sig( DIE => 'sig_DIE' );
1914 $poe_kernel->yield( 'some_event' );
1915 }
1916
1917 sub some_event {
1918 die "I didn't like that!";
1919 }
1920
1921 sub sig_DIE {
1922 my( $sig, $ex ) = @_[ ARG0, ARG1 ];
1923 # $sig is 'DIE'
1924 # $ex is the exception hash
1925 warn "$$: error in $ex->{event}: $ex->{error_str}";
1926 $poe_kernel->sig_handled();
1927
1928 # Send the signal to session that sent the original event.
1929 if( $ex->{source_session} ne $_[SESSION] ) {
1930 $poe_kernel->signal( $ex->{source_session}, 'DIE', $sig, $ex );
1931 }
1932 }
1933
1934 POE::Kernel's built-in exception handling can be disabled by setting
1935 the "POE::Kernel::CATCH_EXCEPTIONS" constant to zero. As with other
1936 compile-time configuration constants, it must be set before POE::Kernel
1937 is compiled:
1938
1939 BEGIN {
1940 package POE::Kernel;
1941 use constant CATCH_EXCEPTIONS => 0;
1942 }
1943 use POE;
1944
1945 or
1946
1947 sub POE::Kernel::CATCH_EXCEPTIONS () { 0 }
1948 use POE;
1949
1950 Signal Watcher Methods
1951 And finally the methods themselves.
1952
1953 sig SIGNAL_NAME [, EVENT_NAME]
1954
1955 sig() registers or unregisters an EVENT_NAME event for a particular
1956 SIGNAL_NAME. The event is registered if EVENT_NAME is defined,
1957 otherwise the SIGNAL_NAME handler is unregistered. This means that a
1958 session can register only one handler per SIGNAL_NAME; subsequent
1959 registration attempts will replace the old handler.
1960
1961 SIGNAL_NAMEs are generally the same as members of %SIG, with two
1962 exceptions. First, "CLD" is an alias for "CHLD" (although see
1963 "sig_child"). And second, it's possible to send and handle signals
1964 created by the application and have no basis in the operating system.
1965
1966 sub handle_start {
1967 $_[KERNEL]->sig( INT => "event_ui_shutdown" );
1968 $_[KERNEL]->sig( bat => "holy_searchlight_batman" );
1969 $_[KERNEL]->sig( signal => "main_screen_turn_on" );
1970 }
1971
1972 The operating system may never be able to generate the last two
1973 signals, but a POE session can by using POE::Kernel's "signal"()
1974 method.
1975
1976 Later on the session may decide not to handle the signals:
1977
1978 sub handle_ui_shutdown {
1979 $_[KERNEL]->sig( "INT" );
1980 $_[KERNEL]->sig( "bat" );
1981 $_[KERNEL]->sig( "signal" );
1982 }
1983
1984 More than one session may register interest in the same signal, and a
1985 session may clear its own signal watchers without affecting those in
1986 other sessions.
1987
1988 sig() does not return a meaningful value.
1989
1990 sig_child PROCESS_ID [, EVENT_NAME]
1991
1992 sig_child() is a convenient way to deliver an EVENT_NAME event when a
1993 particular PROCESS_ID has exited. The watcher can be cleared
1994 prematurely by calling sig_child() with just the PROCESS_ID.
1995
1996 A session may register as many sig_child() handlers as necessary, but a
1997 session may only have one per PROCESS_ID.
1998
1999 sig_child() watchers are one-shot. They automatically unregister
2000 themselves once the EVENT_NAME has been delivered.
2001
2002 sig_child() watchers keep a session alive for as long as they are
2003 active. This is unique among signal watchers.
2004
2005 Programs that wish to reliably reap child processes should be sure to
2006 call sig_child() before returning from the event handler that forked
2007 the process. Otherwise POE::Kernel may have an opportunity to call
2008 waitpid() before an appropriate event watcher has been registered.
2009
2010 sig_child() does not return a meaningful value.
2011
2012 sub forked_parent {
2013 my( $heap, $pid, $details ) = @_[ HEAP, ARG0, ARG1 ];
2014 $heap->{$pid} = $details;
2015 $poe_kernel->sig_child( $pid, 'sig_child' );
2016 }
2017
2018 sub sig_child {
2019 my( $heap, $sig, $pid, $exit_val ) = @_[ HEAP, ARG0, ARG1, ARG2 ];
2020 my $details = delete $heap->{ $pid };
2021 warn "$$: Child $pid exited"
2022 # ....
2023 }
2024
2025 sig_handled
2026
2027 sig_handled() informs POE::Kernel that the currently dispatched signal
2028 has been handled by the currently active session. If the signal is
2029 terminal, the sig_handled() call prevents POE::Kernel from stopping the
2030 sessions that received the signal.
2031
2032 A single signal may be dispatched to several sessions. Only one needs
2033 to call sig_handled() to prevent the entire group from being stopped.
2034 If none of them call it, however, then they are all stopped together.
2035
2036 sig_handled() does not return a meaningful value.
2037
2038 sub _start {
2039 $_[KERNEL]->sig( INT => 'sig_INT' );
2040 }
2041
2042 sub sig_INT {
2043 warn "$$ SIGINT";
2044 $_[KERNEL]->sig_handled();
2045 }
2046
2047 signal SESSION, SIGNAL_NAME [, ARGS_LIST]
2048
2049 signal() posts a SIGNAL_NAME signal to a specific SESSION with an
2050 optional ARGS_LIST that will be passed to every interested handler. As
2051 mentioned elsewhere, the signal may be delivered to SESSION's children,
2052 grandchildren, and so on. And if SESSION is the POE::Kernel itself,
2053 then all interested sessions will receive the signal.
2054
2055 It is possible to send a signal in POE that doesn't exist in the
2056 operating system. signal() places the signal directly into POE's event
2057 queue as if they came from the operating system, but they are not
2058 limited to signals recognized by kill(). POE uses a few of these
2059 fictitious signals for its own global notifications.
2060
2061 For example:
2062
2063 sub some_event_handler {
2064 # Turn on all main screens.
2065 $_[KERNEL]->signal( $_[KERNEL], "signal" );
2066 }
2067
2068 signal() returns true on success. On failure, it returns false after
2069 setting $! to explain the nature of the failure:
2070
2071 ESRCH ("No such process")
2072 The SESSION does not exist.
2073
2074 Because all sessions are a child of POE::Kernel, sending a signal to
2075 the kernel will propagate the signal to all sessions. This is a cheap
2076 form of multicast.
2077
2078 $_[KERNEL]->signal( $_[KERNEL], 'shutdown' );
2079
2080 signal_ui_destroy WIDGET_OBJECT
2081
2082 signal_ui_destroy() associates the destruction of a particular
2083 WIDGET_OBJECT with the complete destruction of the program's user
2084 interface. When the WIDGET_OBJECT destructs, POE::Kernel issues the
2085 non-maskable UIDESTROY signal, which quickly triggers mass destruction
2086 of all active sessions. POE::Kernel->run() returns shortly thereafter.
2087
2088 sub setup_ui {
2089 $_[HEAP]{main_widget} = Gtk->new("toplevel");
2090 # ... populate the main widget here ...
2091 $_[KERNEL]->signal_ui_destroy( $_[HEAP]{main_widget} );
2092 }
2093
2094 Detecting widget destruction is specific to each toolkit.
2095
2096 TODO
2097
2098 TODO - See if there is anything to migrate over from POE::Session?
2099
2100 Event Handler Management
2101 Event handler management methods let sessions hot swap their event
2102 handlers at run time. For example, the POE::Wheel objects use state()
2103 to dynamically mix their own event handlers into the sessions that
2104 create them.
2105
2106 These methods only affect the current session; it would be rude to
2107 change another session's handlers.
2108
2109 There is only one method in this group. Since it may be called in
2110 several different ways, it may be easier to understand if each is
2111 documented separately.
2112
2113 state EVENT_NAME [, CODE_REFERNCE]
2114
2115 state() sets or removes a handler for EVENT_NAME in the current
2116 session. The function referred to by CODE_REFERENCE will be called
2117 whenever EVENT_NAME events are dispatched to the current session. If
2118 CODE_REFERENCE is omitted, the handler for EVENT_NAME will be removed.
2119
2120 A session may only have one handler for a given EVENT_NAME. Subsequent
2121 attempts to set an EVENT_NAME handler will replace earlier handlers
2122 with the same name.
2123
2124 # Stop paying attention to input. Say goodbye, and
2125 # trigger a socket close when the message is sent.
2126 sub send_final_response {
2127 $_[HEAP]{wheel}->put("KTHXBYE");
2128 $_[KERNEL]->state( 'on_client_input' );
2129 $_[KERNEL]->state( on_flush => \&close_connection );
2130 }
2131
2132 state EVENT_NAME [, OBJECT_REFERENCE [, OBJECT_METHOD_NAME] ]
2133
2134 Set or remove a handler for EVENT_NAME in the current session. If an
2135 OBJECT_REFERENCE is given, that object will handle the event. An
2136 optional OBJECT_METHOD_NAME may be provided. If the method name is not
2137 given, POE will look for a method matching the EVENT_NAME instead. If
2138 the OBJECT_REFERENCE is omitted, the handler for EVENT_NAME will be
2139 removed.
2140
2141 A session may only have one handler for a given EVENT_NAME. Subsequent
2142 attempts to set an EVENT_NAME handler will replace earlier handlers
2143 with the same name.
2144
2145 $_[KERNEL]->state( 'some_event', $self );
2146 $_[KERNEL]->state( 'other_event', $self, 'other_method' );
2147
2148 state EVENT_NAME [, CLASS_NAME [, CLASS_METHOD_NAME] ]
2149
2150 This form of state() call is virtually identical to that of the object
2151 form.
2152
2153 Set or remove a handler for EVENT_NAME in the current session. If an
2154 CLASS_NAME is given, that class will handle the event. An optional
2155 CLASS_METHOD_NAME may be provided. If the method name is not given,
2156 POE will look for a method matching the EVENT_NAME instead. If the
2157 CLASS_NAME is omitted, the handler for EVENT_NAME will be removed.
2158
2159 A session may only have one handler for a given EVENT_NAME. Subsequent
2160 attempts to set an EVENT_NAME handler will replace earlier handlers
2161 with the same name.
2162
2163 $_[KERNEL]->state( 'some_event', __PACKAGE__ );
2164 $_[KERNEL]->state( 'other_event', __PACKAGE__, 'other_method' );
2165
2166 Public Reference Counters
2167 The methods in this section manipulate reference counters on the
2168 current session or another session.
2169
2170 Each session has a namespace for user-manipulated reference counters.
2171 These namespaces are associated with the target SESSION_ID for the
2172 reference counter methods, not the caller. Nothing currently prevents
2173 one session from decrementing a reference counter that was incremented
2174 by another, but this behavior is not guaranteed to remain. For now,
2175 it's up to the users of these methods to choose obscure counter names
2176 to avoid conflicts.
2177
2178 Reference counting is a big part of POE's magic. Various objects
2179 (mainly event watchers and components) hold references to the sessions
2180 that own them. "Session Lifespans" explains the concept in more
2181 detail.
2182
2183 The ability to keep a session alive is sometimes useful in an
2184 application or library. For example, a component may hold a public
2185 reference to another session while it processes a request from that
2186 session. In doing so, the component guarantees that the requester is
2187 still around when a response is eventually ready. Keeping a reference
2188 to the session's object is not enough. POE::Kernel has its own
2189 internal reference counting mechanism.
2190
2191 refcount_increment SESSION_ID, COUNTER_NAME
2192
2193 refcount_increment() increases the value of the COUNTER_NAME reference
2194 counter for the session identified by a SESSION_ID. To discourage the
2195 use of session references, the refcount_increment() target session must
2196 be specified by its session ID.
2197
2198 The target session will not stop until the value of any and all of its
2199 COUNTER_NAME reference counters are zero. (Actually, it may stop in
2200 some cases, such as failing to handle a terminal signal.)
2201
2202 Negative reference counters are legal. They still must be incremented
2203 back to zero before a session is eligible for stopping.
2204
2205 sub handle_request {
2206 # Among other things, hold a reference count on the sender.
2207 $_[KERNEL]->refcount_increment( $_[SENDER]->ID, "pending request");
2208 $_[HEAP]{requesters}{$request_id} = $_[SENDER]->ID;
2209 }
2210
2211 For this to work, the session needs a way to remember the
2212 $_[SENDER]->ID for a given request. Customarily the session generates
2213 a request ID and uses that to track the request until it is fulfilled.
2214
2215 refcount_increment() returns true on success or false on failure.
2216 Furthermore, $! is set on failure to one of:
2217
2218 ESRCH: The SESSION_ID does not refer to a currently active session.
2219
2220 refcount_decrement SESSION_ID, COUNTER_NAME
2221
2222 refcount_decrement() reduces the value of the COUNTER_NAME reference
2223 counter for the session identified by a SESSION_ID. It is the
2224 counterpoint for refcount_increment(). Please see refcount_increment()
2225 for more context.
2226
2227 sub finally_send_response {
2228 # Among other things, release the reference count for the
2229 # requester.
2230 my $requester_id = delete $_[HEAP]{requesters}{$request_id};
2231 $_[KERNEL]->refcount_decrement( $requester_id, "pending request");
2232 }
2233
2234 The requester's $_[SENDER]->ID is remembered and removed from the heap
2235 (lest there be memory leaks). It's used to decrement the reference
2236 counter that was incremented at the start of the request.
2237
2238 refcount_decrement() returns true on success or false on failure.
2239 Furthermore, $! is set on failure to one of:
2240
2241 ESRCH: The SESSION_ID does not refer to a currently active session.
2242
2243 It is not possible to discover currently active public references. See
2244 POE::API::Peek.
2245
2246 Kernel State Accessors
2247 POE::Kernel provides a few accessors into its massive brain so that
2248 library developers may have convenient access to necessary data without
2249 relying on their callers to provide it.
2250
2251 These accessors expose ways to break session encapsulation. Please use
2252 them sparingly and carefully.
2253
2254 get_active_session
2255
2256 get_active_session() returns a reference to the session that is
2257 currently running, or a reference to the program's POE::Kernel instance
2258 if no session is running at that moment. The value is equivalent to
2259 POE::Session's $_[SESSION].
2260
2261 This method was added for libraries that need $_[SESSION] but don't
2262 want to include it as a parameter in their APIs.
2263
2264 sub some_housekeeping {
2265 my( $self ) = @_;
2266 my $session = $poe_kernel->get_active_session;
2267 # do some housekeeping on $session
2268 }
2269
2270 get_active_event
2271
2272 get_active_event() returns the name of the event currently being
2273 dispatched. It returns an empty string when called outside event
2274 dispatch. The value is equivalent to POE::Session's $_[STATE].
2275
2276 sub waypoint {
2277 my( $message ) = @_;
2278 my $event = $poe_kernel->get_active_event;
2279 print STDERR "$$:$event:$mesage\n";
2280 }
2281
2282 get_event_count
2283
2284 get_event_count() returns the number of events pending in POE's event
2285 queue. It is exposed for POE::Loop class authors. It may be
2286 deprecated in the future.
2287
2288 get_next_event_time
2289
2290 get_next_event_time() returns the time the next event is due, in a form
2291 compatible with the UNIX time() function. It is exposed for POE::Loop
2292 class authors. It may be deprecated in the future.
2293
2294 poe_kernel_loop
2295
2296 poe_kernel_loop() returns the name of the POE::Loop class that is used
2297 to detect and dispatch events.
2298
2299 Session Helper Methods
2300 The methods in this group expose features for POE::Session class
2301 authors.
2302
2303 session_alloc SESSION_OBJECT [, START_ARGS]
2304
2305 session_alloc() allocates a session context within POE::Kernel for a
2306 newly created SESSION_OBJECT. A list of optional START_ARGS will be
2307 passed to the session as part of the "_start" event.
2308
2309 The SESSION_OBJECT is expected to follow a subset of POE::Session's
2310 interface.
2311
2312 There is no session_free(). POE::Kernel determines when the session
2313 should stop and performs the necessary cleanup after dispatching _stop
2314 to the session.
2315
2316 Miscellaneous Methods
2317 We don't know where to classify the methods in this section.
2318
2319 new
2320
2321 It is not necessary to call POE::Kernel's new() method. Doing so will
2322 return the program's singleton POE::Kernel object, however.
2323
2325 POE::Kernel exports two variables for your coding enjoyment:
2326 $poe_kernel and $poe_main_window. POE::Kernel is implicitly used by
2327 POE itself, so using POE gets you POE::Kernel (and its exports) for
2328 free.
2329
2330 In more detail:
2331
2332 $poe_kernel
2333 $poe_kernel contains a reference to the process' POE::Kernel singleton
2334 instance. It's mainly used for accessing POE::Kernel methods from
2335 places where $_[KERNEL] is not available. It's most commonly used in
2336 helper libraries.
2337
2338 $poe_main_window
2339 $poe_main_window is used by graphical toolkits that require at least
2340 one widget to be created before their event loops are usable. This is
2341 currently only Tk.
2342
2343 POE::Loop::Tk creates a main window to satisfy Tk's event loop. The
2344 window is given to the application since POE has no other use for it.
2345
2346 $poe_main_window is undefined in toolkits that don't require a widget
2347 to dispatch events.
2348
2349 On a related note, POE will shut down if the widget in $poe_main_window
2350 is destroyed. This can be changed with POE::Kernel's
2351 "/signal_ui_destroy"() method.
2352
2354 POE includes quite a lot of debugging code, in the form of both fatal
2355 assertions and run-time traces. They may be enabled at compile time,
2356 but there is no way to toggle them at run-time. This was done to avoid
2357 run-time penalties in programs where debugging is not necessary. That
2358 is, in most production cases.
2359
2360 Traces are verbose reminders of what's going on within POE. Each is
2361 prefixed with a four-character field describing the POE subsystem that
2362 generated it.
2363
2364 Assertions (asserts) are quiet but deadly, both in performance (they
2365 cause a significant run-time performance hit) and because they cause
2366 fatal errors when triggered.
2367
2368 The assertions and traces are useful for developing programs with POE,
2369 but they were originally added to debug POE itself.
2370
2371 Each assertion and tracing group is enabled by setting a constant in
2372 the POE::Kernel namespace to a true value. This is the same mechanism
2373 documented under "Using Time::HiRes", namely:
2374
2375 BEGIN {
2376 package POE::Kernel;
2377 use constant ASSERT_DEFAULT => 1;
2378 }
2379 use POE;
2380
2381 or
2382
2383 sub POE::Kernel::ASSERT_DEFAULT () { 1 }
2384 use POE;
2385
2386 As mentioned in "Using Time::HiRes", the switches must be defined as
2387 constants before POE::Kernel is first loaded. Otherwise Perl's
2388 compiler will not see the constants when first compiling POE::Kernel,
2389 and the features will not be properly enabled.
2390
2391 Assertions and traces may also be enabled by setting shell environment
2392 variables. The environment variables are named after the POE::Kernel
2393 constants with a "POE_" prefix.
2394
2395 POE_ASSERT_DEFAULT=1 POE_TRACE_DEFAULT=1 ./my_poe_program
2396
2397 In alphabetical order:
2398
2399 ASSERT_DATA
2400 ASSERT_DATA enables run-time data integrity checks within POE::Kernel
2401 and the classes that mix into it. POE::Kernel tracks a lot of cross-
2402 referenced data, and this group of assertions ensures that it's
2403 consistent.
2404
2405 Prefix: <dt>
2406
2407 Environment variable: POE_ASSERT_DATA
2408
2409 ASSERT_DEFAULT
2410 ASSERT_DEFAULT specifies the default value for assertions that are not
2411 explicitly enabled or disabled. This is a quick and reliable way to
2412 make sure all assertions are on.
2413
2414 No assertion uses ASSERT_DEFAULT directly, and this assertion flag has
2415 no corresponding output prefix.
2416
2417 Turn on all assertions except ASSERT_EVENTS:
2418
2419 sub POE::Kernel::ASSERT_DEFAULT () { 1 }
2420 sub POE::Kernel::ASSERT_EVENTS () { 0 }
2421 use POE::Kernel;
2422
2423 Prefix: (none)
2424
2425 Environment variable: POE_ASSERT_DEFAULT
2426
2427 ASSERT_EVENTS
2428 ASSERT_EVENTS mainly checks for attempts to dispatch events to sessions
2429 that don't exist. This assertion can assist in the debugging of
2430 strange, silent cases where event handlers are not called.
2431
2432 Prefix: <ev>
2433
2434 Environment variable: POE_ASSERT_EVENTS
2435
2436 ASSERT_FILES
2437 ASSERT_FILES enables some run-time checks in POE's filehandle watchers
2438 and the code that manages them.
2439
2440 Prefix: <fh>
2441
2442 Environment variable: POE_ASSERT_FILES
2443
2444 ASSERT_RETVALS
2445 ASSERT_RETVALS upgrades failure codes from POE::Kernel's methods from
2446 advisory return values to fatal errors. Most programmers don't check
2447 the values these methods return, so ASSERT_RETVALS is a quick way to
2448 validate one's assumption that all is correct.
2449
2450 Prefix: <rv>
2451
2452 Environment variable: POE_ASSERT_RETVALS
2453
2454 ASSERT_USAGE
2455 ASSERT_USAGE is the counterpoint to ASSERT_RETVALS. It enables run-
2456 time checks that the parameters to POE::Kernel's methods are correct.
2457 It's a quick (but not foolproof) way to verify a program's use of POE.
2458
2459 Prefix: <us>
2460
2461 Environment variable: POE_ASSERT_USAGE
2462
2463 TRACE_DEFAULT
2464 TRACE_DEFAULT specifies the default value for traces that are not
2465 explicitly enabled or disabled. This is a quick and reliable way to
2466 ensure your program generates copious output on the file named in
2467 TRACE_FILENAME or STDERR by default.
2468
2469 To enable all traces except a few noisier ones:
2470
2471 sub POE::Kernel::TRACE_DEFAULT () { 1 }
2472 sub POE::Kernel::TRACE_EVENTS () { 0 }
2473 use POE::Kernel;
2474
2475 Prefix: (none)
2476
2477 Environment variable: POE_TRACE_DEFAULT
2478
2479 TRACE_DESTROY
2480 TRACE_DESTROY causes every POE::Session object to dump the contents of
2481 its $_[HEAP] when Perl destroys it. This trace was added to help
2482 developers find memory leaks in their programs.
2483
2484 Prefix: A line that reads "----- Session $self Leak Check -----".
2485
2486 Environment variable: POE_TRACE_DESTROY
2487
2488 TRACE_EVENTS
2489 TRACE_EVENTS enables messages pertaining to POE's event queue's
2490 activities: when events are enqueued, dispatched or discarded, and
2491 more. It's great for determining where events go and when.
2492 Understandably this is one of POE's more verbose traces.
2493
2494 Prefix: <ev>
2495
2496 Environment variable: POE_TRACE_EVENTS
2497
2498 TRACE_FILENAME
2499 TRACE_FILENAME specifies the name of a file where POE's tracing and
2500 assertion messages should go. It's useful if you want the messages but
2501 have other plans for STDERR, which is where the messages go by default.
2502
2503 POE's tests use this so the trace and assertion code can be
2504 instrumented during testing without spewing all over the terminal.
2505
2506 Prefix: (none)
2507
2508 Environment variable: POE_TRACE_FILENAME
2509
2510 TRACE_FILES
2511 TRACE_FILES enables or disables traces in POE's filehandle watchers and
2512 the POE::Loop class that implements the lowest-level filehandle
2513 multiplexing. This may be useful when tracking down strange behavior
2514 related to filehandles.
2515
2516 Prefix: <fh>
2517
2518 Environment variable: POE_TRACE_FILES
2519
2520 TRACE_PROFILE
2521 TRACE_PROFILE enables basic profiling within POE's event dispatcher.
2522 When enabled, POE counts the number of times each event is dispatched.
2523 At the end of a run, POE will display a table for each event name and
2524 its dispatch count.
2525
2526 See TRACE_STATISTICS for more profiling.
2527
2528 Prefix: <pr>
2529
2530 Environment variable: POE_TRACE_PROFILE
2531
2532 stat_show_profile
2533
2534 When TRACE_PROFILE is enabled, a program may call
2535 "$_[KERNEL]->stat_show_profile()" to display a current dispatch profile
2536 snapshot.
2537
2538 stat_getprofile [ SESSION ]
2539
2540 stat_getprofile() returns a hash of events and the number of times they
2541 were dispatched. It only returns meaningful data if TRACE_PROFILE is
2542 enabled.
2543
2544 Without the optional SESSION parameter, stat_getprofile() returns
2545 cumulative statistics for the entire program.
2546
2547 When given a valid SESSION, stat_getprofile() will return profile
2548 statistics for that session.
2549
2550 stat_getprofile() returns nothing if TRACE_PROFILE isn't enabled, or if
2551 the given SESSION doesn't exist.
2552
2553 TRACE_REFCNT
2554 TRACE_REFCNT governs whether POE::Kernel will trace sessions' reference
2555 counts. As discussed in "Session Lifespans", POE does a lot of
2556 reference counting, and the current state of a session's reference
2557 counts determines whether the session lives or dies. It's common for
2558 developers to wonder why a session stops too early or remains active
2559 too long. TRACE_REFCNT can help explain why.
2560
2561 Prefix: <rc>
2562
2563 Environment variable: POE_TRACE_REFCNT
2564
2565 TRACE_RETVALS
2566 TRACE_RETVALS can enable carping whenever a POE::Kernel method is about
2567 to fail. It's a non-fatal but noisier form of ASSERT_RETVALS.
2568
2569 Prefix: <rv>
2570
2571 Environment variable: POE_TRACE_RETVALS
2572
2573 TRACE_SESSIONS
2574 TRACE_SESSIONS enables trace messages that pertain to session
2575 management. Notice will be given when sessions are created or
2576 destroyed, and when the parent or child status of a session changes.
2577
2578 Prefix: <ss>
2579
2580 Environment variable: POE_TRACE_SESSIONS
2581
2582 TRACE_SIGNALS
2583 TRACE_SIGNALS turns on (or off) traces in POE's signal handling
2584 subsystem. Signal dispatch is one of POE's more complex parts, and the
2585 trace messages may help application developers understand signal
2586 propagation and timing.
2587
2588 Prefix: <sg>
2589
2590 Environment variable: POE_TRACE_SIGNALS
2591
2592 TRACE_STATISTICS
2593 This feature is experimental, and its interface will likely change.
2594
2595 TRACE_STATISTICS enables run-time gathering and reporting of various
2596 performance metrics within a POE program. Some statistics include how
2597 much time is spent processing event handlers, time spent in POE's
2598 dispatcher, and the time spent waiting for an event. A report is
2599 displayed just before run() returns, and the data can be retrieved at
2600 any time using stat_getdata().
2601
2602 See POE::Resource::Statistics for more details about POE's statistics.
2603
2604 stat_getdata
2605
2606 stat_getdata() returns a hash of various statistics and their values
2607 The statistics are calculated using a sliding window and vary over time
2608 as a program runs. It only returns meaningful data if TRACE_STATISTICS
2609 is enabled.
2610
2611 See "Gathered Statistics" in POE::Resource::Statistics for details
2612 about what is gathered.
2613
2615 These additional constants govern POE's operation.
2616
2617 USE_TIME_HIRES
2618 Whether or not to use Time::HiRes for timing purposes.
2619
2620 See "Using Time::HiRes".
2621
2622 USE_SIGCHLD
2623 Whether to use $SIG{CHLD} or to poll at an interval.
2624
2625 This flag is disabled by default, and enabling it may cause breakage
2626 under older perls with no safe signals, and under Apache which uses
2627 $SIG{CHLD}.
2628
2629 Enabling this flag will cause child reaping to happen almost
2630 immediately, as opposed to once per "CHILD_POLLING_INTERVAL".
2631
2632 CHILD_POLLING_INTERVAL
2633 The interval at which "wait" is called to determine if child processes
2634 need to be reaped and the "CHLD" signal emulated.
2635
2636 Defaults to 1 second.
2637
2638 USE_SIGNAL_PIPE
2639 The only safe way to handle signals is to implement a shared-nothing
2640 model. POE builds a signal pipe that communicates between the signal
2641 handlers and the POE kernel loop in a safe and atomic manner. The
2642 signal pipe is implemented with POE::Pipe::OneWay, using a "pipe"
2643 conduit on Unix. Unfortunately, the signal pipe is not compatible with
2644 Windows and is not used on that platform.
2645
2646 If you wish to revert to the previous unsafe signal behaviour, you must
2647 set "USE_SIGNAL_PIPE" to 0, or the environment variable
2648 "POE_USE_SIGNAL_PIPE".
2649
2650 CATCH_EXCEPTIONS
2651 Whether or not POE should run event handler code in an eval { } and
2652 deliver the "DIE" signal on errors.
2653
2654 See "Exception Handling".
2655
2657 POE's tests are lovely, dark and deep. These environment variables
2658 allow testers to take roads less traveled.
2659
2660 POE_DANTIC
2661 Windows and Perls built for it tend to be poor at doing UNIXy things,
2662 although they do try. POE being very UNIXy itself must skip a lot of
2663 Windows tests. The POE_DANTIC environment variable will, when true,
2664 enable all these tests. It's intended to be used from time to time to
2665 see whether Windows has improved in some area.
2666
2668 The SEE ALSO section in POE contains a table of contents covering the
2669 entire POE distribution.
2670
2672 · There is no mechanism in place to prevent external reference count
2673 names from clashing.
2674
2675 · There is no mechanism to catch exceptions generated in another
2676 session.
2677
2679 Please see POE for more information about authors and contributors.
2680
2681
2682
2683perl v5.12.1 2010-04-03 POE::Kernel(3)