.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "POE::Kernel 3pm" .TH POE::Kernel 3pm "2020-02-07" "perl v5.30.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" POE::Kernel \- an event\-based application kernel in Perl .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use POE; # auto\-includes POE::Kernel and POE::Session \& \& POE::Session\->create( \& inline_states => { \& _start => sub { $_[KERNEL]\->yield("next") }, \& next => sub { \& print "tick...\en"; \& $_[KERNEL]\->delay(next => 1); \& }, \& }, \& ); \& \& POE::Kernel\->run(); \& exit; .Ve .PP In the spirit of Perl, there are a lot of other ways to use \s-1POE.\s0 .SH "DESCRIPTION" .IX Header "DESCRIPTION" POE::Kernel is the heart of \s-1POE.\s0 It provides the lowest-level features: non-blocking multiplexed I/O, timers, and signal watchers are the most significant. Everything else is built upon this foundation. .PP POE::Kernel is not an event loop in itself. For that it uses one of several available POE::Loop interface modules. See \s-1CPAN\s0 for modules in the POE::Loop namespace. .PP \&\s-1POE\s0's documentation assumes the reader understands the \f(CW@_\fR offset constants (\s-1KERNEL, HEAP, ARG0,\s0 etc.). The curious or confused reader will find more detailed explanation in POE::Session. .SH "USING POE" .IX Header "USING POE" .SS "Literally Using \s-1POE\s0" .IX Subsection "Literally Using POE" \&\s-1POE\s0.pm is little more than a class loader. It implements some magic to cut down on the setup work. .PP Parameters to \f(CW\*(C`use POE\*(C'\fR are not treated as normal imports. Rather, they're abbreviated modules to be included along with \s-1POE.\s0 .PP .Vb 1 \& use POE qw(Component::Client::TCP). .Ve .PP As you can see, the leading \*(L"\s-1POE::\*(R"\s0 can be omitted this way. .PP \&\s-1POE\s0.pm also includes POE::Kernel and POE::Session by default. These two modules are used by nearly all POE-based programs. So the above example is actually the equivalent of: .PP .Vb 4 \& use POE; \& use POE::Kernel; \& use POE::Session; \& use POE::Component::Client::TCP; .Ve .SS "Using POE::Kernel" .IX Subsection "Using POE::Kernel" POE::Kernel needs to know which event loop you want to use. This is supported in three different ways: .PP The first way is to use an event loop module before using POE::Kernel (or \s-1POE,\s0 which loads POE::Kernel for you): .PP .Vb 2 \& use Tk; # or one of several others \& use POE::Kernel. .Ve .PP POE::Kernel scans the list of modules already loaded, and it loads an appropriate POE::Loop adapter if it finds a known event loop. .PP The next way is to explicitly load the POE::Loop class you want: .PP .Vb 1 \& use POE qw(Loop::Gtk); .Ve .PP Finally POE::Kernel's \f(CW\*(C`import()\*(C'\fR supports more programmer-friendly configuration: .PP .Vb 2 \& use POE::Kernel { loop => "Gtk" }; \& use POE::Session; .Ve .SS "Anatomy of a POE-Based Application" .IX Subsection "Anatomy of a POE-Based Application" Programs using \s-1POE\s0 work like any other. They load required modules, perform some setup, run some code, and eventually exit. Halting Problem notwithstanding. .PP A POE-based application loads some modules, sets up one or more sessions, runs the code in those sessions, and eventually exits. .PP .Vb 4 \& use POE; \& POE::Session\->create( ... map events to code here ... ); \& POE::Kernel\->run(); \& exit; .Ve .SS "POE::Kernel singleton" .IX Subsection "POE::Kernel singleton" The POE::Kernel is a singleton object; there can be only one POE::Kernel instance within a process. This allows many object methods to also be package methods. .SS "Sessions" .IX Subsection "Sessions" \&\s-1POE\s0 implements isolated compartments called \fIsessions\fR. Sessions play the role of tasks or threads within \s-1POE.\s0 POE::Kernel acts as \s-1POE\s0's task scheduler, doling out timeslices to each session by invoking callbacks within them. .PP Callbacks are not preemptive. As long as one is running, no others will be dispatched. This is known as \fIcooperative\fR multitasking. Each session must cooperate by returning to the central dispatching kernel. .PP Cooperative multitasking vastly simplifies data sharing, since no two pieces of code may alter data at once. .PP A session may also take exclusive control of a program's time, if necessary, by simply not returning in a timely fashion. It's even possible to write completely blocking programs that use \s-1POE\s0 as a state machine rather than a cooperative dispatcher. .PP Every POE-based application needs at least one session. Code cannot run \fIwithin \s-1POE\s0\fR without being a part of some session. Likewise, a threaded program always has a \*(L"thread zero\*(R". .PP Sessions in POE::Kernel should not be confused with POE::Session even though the two are inextricably associated. POE::Session adapts POE::Kernel's dispatcher to a particular calling convention. Other POE::Session classes exist on the \s-1CPAN.\s0 Some radically alter the way event handlers are called. . .SS "Resources" .IX Subsection "Resources" Resources are events and things which may create new events, such as timers, I/O watchers, and even other sessions. .PP POE::Kernel tracks resources on behalf of its active sessions. It generates events corresponding to these resources' activity, notifying sessions when it's time to do things. .PP The conversation goes something like this: .PP .Vb 2 \& Session: Be a dear, Kernel, and let me know when someone clicks on \& this widget. Thanks so much! \& \& [TIME PASSES] [SFX: MOUSE CLICK] \& \& Kernel: Right, then. Someone\*(Aqs clicked on your widget. \& Here you go. .Ve .PP Furthermore, since the Kernel keeps track of everything sessions do, it knows when a session has run out of tasks to perform. When this happens, the Kernel emits a \f(CW\*(C`_stop\*(C'\fR event at the dead session so it can clean up and shutdown. .PP .Vb 1 \& Kernel: Please switch off the lights and lock up; it\*(Aqs time to go. .Ve .PP Likewise, if a session stops on its own and there still are opened resource watchers, the Kernel knows about them and cleans them up on the session's behalf. \s-1POE\s0 excels at long-running services because it so meticulously tracks and cleans up resources. .PP POE::Resources and the POE::Resource classes implement each kind of resource, which are summarized here and covered in greater detail later. .IP "Events." 2 .IX Item "Events." An event is a message to a sessions. Posting an event keeps both the sender and the receiver alive until after the event has been dispatched. This is only guaranteed if both the sender and receiver are in the same process. Inter-Kernel message passing add-ons may have other guarantees. Please see their documentation for details. .Sp The rationale is that the event is in play, so the receiver must remain active for it to be dispatched. The sender remains alive in case the receiver would like to send back a response. .Sp Posted events cannot be preemptively canceled. They tend to be short-lived in practice, so this generally isn't an issue. .IP "Timers." 2 .IX Item "Timers." Timers allow an application to send a message to the future. Once set, a timer will keep the destination session active until it goes off and the resulting event is dispatched. .IP "Aliases." 2 .IX Item "Aliases." Session aliases are an application-controlled way of addressing a session. Aliases act as passive event watchers. As long as a session has an alias, some other session may send events to that session by that name. Aliases keep sessions alive as long as a process has active sessions. .Sp If the only sessions remaining are being kept alive solely by their aliases, POE::Kernel will send them a terminal \*(L"\s-1IDLE\*(R"\s0 signal. In most cases this will terminate the remaining sessions and allow the program to exit. If the sessions remain in memory without waking up on the \f(CW\*(C`IDLE\*(C'\fR signal, POE::Kernel sends them a non-maskable \*(L"\s-1ZOMBIE\*(R"\s0 signal. They are then forcibly removed, and the program will finally exit. .IP "I/O watchers." 2 .IX Item "I/O watchers." A session will remain active as long as a session is paying attention to some external data source or sink. See select_read and select_write. .IP "Child sessions." 2 .IX Item "Child sessions." A session acting as a parent of one or more other sessions will remain active until all the child sessions stop. This may be bypassed by detaching the children from the parent. .IP "Child processes." 2 .IX Item "Child processes." Child process are watched by \fBsig_child()\fR. The \fBsig_child()\fR watcher will keep the watching session active until the child process has been reaped by POE::Kernel and the resulting event has been dispatched. .Sp All other signal watchers, including using \*(L"sig\*(R" to watch for \&\f(CW\*(C`CHLD\*(C'\fR, do not keep their sessions active. If you need a session to remain active when it's only watching for signals, have it set an alias or one of its own public reference counters. .IP "Public reference counters." 2 .IX Item "Public reference counters." A session will remain active as long as it has one or more nonzero public (or external) reference counter. .SS "Session Lifespans" .IX Subsection "Session Lifespans" \&\*(L"Session\*(R" as a term is somewhat overloaded. There are two related concepts that share the name. First there is the class POE::Session, and objects created with it or related classes. Second there is a data structure within POE::Kernel that tracks the POE::Session objects in play and the various resources owned by each. .PP The way \s-1POE\s0's garbage collector works is that a session object gives itself to POE::Kernel at creation time. The Kernel then holds onto that object as long as resources exist that require the session to remain alive. When all of these resources are destroyed or released, the session object has nothing left to trigger activity. POE::Kernel notifies the object it's through, and cleans up its internal session context. The session object is released, and self-destructs in the normal Perlish fashion. .PP Sessions may be stopped even if they have active resources. For example, a session may fail to handle a terminal signal. In this case, POE::Kernel forces the session to stop, and all resources associated with the session are preemptively released. .SS "Events" .IX Subsection "Events" An event is a message that is sent from one part of the \s-1POE\s0 application to another. An event consists of the event's name, optional event-specific parameters and \s-1OOB\s0 information. An event may be sent from the kernel, from a wheel or from a session. .PP An application creates an event with \*(L"post\*(R", \*(L"yield\*(R", \*(L"call\*(R" or even \*(L"signal\*(R". POE::Kernel creates events in response external stimulus (signals, select, etc). .PP \fIEvent Handlers\fR .IX Subsection "Event Handlers" .PP An event is handled by a function called an \fIevent handler\fR, which is some code that is designated to be called when a particular event is dispatched. See \*(L"Event Handler Management\*(R" and POE::Session. .PP The term \fIstate\fR is often used in place of \fIevent handler\fR, especially when treating sessions as event driven state machines. .PP Handlers are always called in scalar context for asynchronous events (i.e. via \fBpost()\fR). Synchronous events, invoked with \fBcall()\fR, are handled in the same context that \fBcall()\fR was called. .PP Event handlers may not directly return references to objects in the \&\*(L"\s-1POE\*(R"\s0 namespace. POE::Kernel will stringify these references to prevent timing issues with certain objects' destruction. For example, this error handler would cause errors because a deleted wheel would not be destructed when one might think: .PP .Vb 4 \& sub handle_error { \& warn "Got an error"; \& delete $_[HEAP]{wheel}; \& } .Ve .PP The \fBdelete()\fR call returns the deleted wheel member, which is then returned implicitly by \fBhandle_error()\fR. .SS "Using \s-1POE\s0 with Other Event Loops" .IX Subsection "Using POE with Other Event Loops" POE::Kernel supports any number of event loops. Two are included in the base distribution. Historically, \s-1POE\s0 included other loops but they were moved into a separate distribution. You can find them and other loops on the \s-1CPAN.\s0 .PP \&\s-1POE\s0's public interfaces remain the same regardless of the event loop being used. Since most graphical toolkits include some form of event loop, back-end code should be portable to all of them. .PP \&\s-1POE\s0's cooperation with other event loops lets \s-1POE\s0 be embedded into other software. The common underlying event loop drives both the application and \s-1POE.\s0 For example, by using POE::Loop::Glib, one can embed \s-1POE\s0 into Vim, irssi, and so on. Application scripts can then take advantage of POE::Component::Client::HTTP (and everything else) to do large-scale work without blocking the rest of the program. .PP Because this is Perl, there are multiple ways to load an alternate event loop. The simplest way is to load the event loop before loading POE::Kernel. .PP .Vb 2 \& use Gtk; \& use POE; .Ve .PP Remember that \s-1POE\s0 loads POE::Kernel internally. .PP POE::Kernel examines the modules loaded before it and detects that Gtk has been loaded. If POE::Loop::Gtk is available, \s-1POE\s0 loads and hooks it into POE::Kernel automatically. .PP It's less mysterious to load the appropriate POE::Loop class directly. Their names follow the format \&\f(CW\*(C`POE::Loop::$loop_module_name\*(C'\fR, where \f(CW$loop_module_name\fR is the name of the event loop module after each \f(CW\*(C`::\*(C'\fR has been substituted with an underscore. It can be abbreviated using \s-1POE\s0's loader magic. .PP .Vb 1 \& use POE qw( Loop::Event_Lib ); .Ve .PP \&\s-1POE\s0 also recognizes \s-1XS\s0 loops, they reside in the \&\f(CW\*(C`POE::XS::Loop::$loop_module_name\*(C'\fR namespace. Using them may give you a performance improvement on your platform, as the eventloop are some of the hottest code in the system. As always, benchmark your application against various loops to see which one is best for your workload and platform. .PP .Vb 1 \& use POE qw( XS::Loop::EPoll ); .Ve .PP Please don't load the loop modules directly, because \s-1POE\s0 will not have a chance to initialize it's internal structures yet. Code written like this will throw errors on startup. It might look like a bug in \s-1POE,\s0 but it's just the way \s-1POE\s0 is designed. .PP .Vb 2 \& use POE::Loop::IO_Poll; \& use POE; .Ve .PP POE::Kernel also supports configuration directives on its own \f(CW\*(C`use\*(C'\fR line. A loop explicitly specified this way will override the search logic. .PP .Vb 1 \& use POE::Kernel { loop => "Glib" }; .Ve .PP Finally, one may specify the loop class by setting the POE::Loop or POE::XS:Loop class name in the \s-1POE_EVENT_LOOP\s0 environment variable. This mechanism was added for tests that need to specify the loop from a distance. .PP .Vb 2 \& BEGIN { $ENV{POE_EVENT_LOOP} = "POE::XS::Loop::Poll" } \& use POE; .Ve .PP Of course this may also be set from your shell: .PP .Vb 2 \& % export POE_EVENT_LOOP=\*(AqPOE::XS::Loop::Poll\*(Aq \& % make test .Ve .PP Many external event loops support their own callback mechanisms. POE::Session's \*(L"\fBpostback()\fR\*(R" and \*(L"\fBcallback()\fR\*(R" methods return plain Perl code references that will generate \s-1POE\s0 events when called. Applications can pass these code references to event loops for use as callbacks. .PP \&\s-1POE\s0's distribution includes two event loop interfaces. \s-1CPAN\s0 holds several more: .PP \fIPOE::Loop::Select (bundled)\fR .IX Subsection "POE::Loop::Select (bundled)" .PP By default \s-1POE\s0 uses its \fBselect()\fR based loop to drive its event system. This is perhaps the least efficient loop, but it is also the most portable. \s-1POE\s0 optimizes for correctness above all. .PP \fIPOE::Loop::IO_Poll (bundled)\fR .IX Subsection "POE::Loop::IO_Poll (bundled)" .PP The IO::Poll event loop provides an alternative that theoretically scales better than \fBselect()\fR. .PP \fIPOE::Loop::Event (separate distribution)\fR .IX Subsection "POE::Loop::Event (separate distribution)" .PP This event loop provides interoperability with other modules that use Event. It may also provide a performance boost because Event is written in a compiled language. Unfortunately, this makes Event less portable than Perl's built-in \fBselect()\fR. .PP \fIPOE::Loop::Gtk (separate distribution)\fR .IX Subsection "POE::Loop::Gtk (separate distribution)" .PP This event loop allows programs to work under the Gtk graphical toolkit. .PP \fIPOE::Loop::Tk (separate distribution)\fR .IX Subsection "POE::Loop::Tk (separate distribution)" .PP This event loop allows programs to work under the Tk graphical toolkit. Tk has some restrictions that require \s-1POE\s0 to behave oddly. .PP Tk's event loop will not run unless one or more widgets are created. \&\s-1POE\s0 must therefore create such a widget before it can run. POE::Kernel exports \f(CW$poe_main_window\fR so that the application developer may use the widget (which is a MainWindow), since \s-1POE\s0 doesn't need it other than for dispatching events. .PP Creating and using a different MainWindow often has an undesired outcome. .PP \fIPOE::Loop::EV (separate distribution)\fR .IX Subsection "POE::Loop::EV (separate distribution)" .PP POE::Loop::EV allows POE-based programs to use the \s-1EV\s0 event library with little or no change. .PP \fIPOE::Loop::Glib (separate distribution)\fR .IX Subsection "POE::Loop::Glib (separate distribution)" .PP POE::Loop::Glib allows POE-based programs to use Glib with little or no change. It also supports embedding POE-based programs into applications that already use Glib. For example, we have heard that \&\s-1POE\s0 has successfully embedded into vim, irssi and xchat via this loop. .PP \fIPOE::Loop::Kqueue (separate distribution)\fR .IX Subsection "POE::Loop::Kqueue (separate distribution)" .PP POE::Loop::Kqueue allows POE-based programs to transparently use the \s-1BSD\s0 kqueue event library on operating systems that support it. .PP \fIPOE::Loop::Prima (separate distribution)\fR .IX Subsection "POE::Loop::Prima (separate distribution)" .PP POE::Loop::Prima allows POE-based programs to use Prima's event loop with little or no change. It allows \s-1POE\s0 libraries to be used within Prima applications. .PP \fIPOE::Loop::Wx (separate distribution)\fR .IX Subsection "POE::Loop::Wx (separate distribution)" .PP POE::Loop::Wx allows POE-based programs to use Wx's event loop with little or no change. It allows \s-1POE\s0 libraries to be used within Wx applications, such as Padre. .PP \fIPOE::XS::Loop::EPoll (separate distribution)\fR .IX Subsection "POE::XS::Loop::EPoll (separate distribution)" .PP POE::XS::Loop::EPoll allows \s-1POE\s0 components to transparently use the EPoll event library on operating systems that support it. .PP \fIPOE::XS::Loop::Poll (separate distribution)\fR .IX Subsection "POE::XS::Loop::Poll (separate distribution)" .PP POE::XS::Loop::Poll is a higher-performance C\-based libpoll event loop. It replaces some of \s-1POE\s0's hot Perl code with C for better performance. .PP \fIOther Event Loops (separate distributions)\fR .IX Subsection "Other Event Loops (separate distributions)" .PP \&\s-1POE\s0 may be extended to handle other event loops. Developers are invited to work with us to support their favorite loops. .SH "PUBLIC METHODS" .IX Header "PUBLIC METHODS" POE::Kernel encapsulates a lot of features. The documentation for each set of features is grouped by purpose. .SS "Kernel Management and Accessors" .IX Subsection "Kernel Management and Accessors" \fI\s-1ID\s0\fR .IX Subsection "ID" .PP \&\s-1\fBID\s0()\fR currently returns POE::Kernel's unique identifier. Every Kernel instance is assigned a globally unique \s-1ID\s0 at birth. \&\fBhas_forked()\fR alters the \s-1ID\s0 so that each forked process has a unique one, too. .PP .Vb 2 \& % perl \-wl \-MPOE \-e \*(Aqprint $poe_kernel\->ID\*(Aq \& macbookpoe.local\-4d5305de\-0000e6b8\-00000001 .Ve .PP The content of these IDs may change from time to time. Your code should not depend upon the current format. .PP \&\fBDeprecation Warning 2011\-02\-09\fR .PP Your code should not depend upon \s-1\fBID\s0()\fR remaining unique. The uniqueness will be removed in a future release of \s-1POE.\s0 If you require unique IDs, please see one of the fine \s-1GUID\s0 and/or \s-1UUID\s0 modules on the \&\s-1CPAN:\s0 .PP .Vb 2 \& http://search.cpan.org/search?query=GUID&mode=dist \& http://search.cpan.org/search?query=UUID&mode=dist .Ve .PP \&\s-1POE\s0 doesn't require globally or universally unique kernel IDs. The creation and maintenance of these IDs adds overhead to POE::Kernel's \&\fBhas_forked()\fR method. Other modules do it better, upon demand, without incurring overhead for those who don't need them. .PP \fIrun\fR .IX Subsection "run" .PP \&\fBrun()\fR runs POE::Kernel's event dispatcher. It will not return until all sessions have ended. \fBrun()\fR is a class method so a POE::Kernel reference is not needed to start a program's execution. .PP .Vb 4 \& use POE; \& POE::Session\->create( ... ); # one or more \& POE::Kernel\->run(); # set them all running \& exit; .Ve .PP \&\s-1POE\s0 implements the Reactor pattern at its core. Events are dispatched to functions and methods through callbacks. The code behind \fBrun()\fR waits for and dispatches events. .PP \&\fBrun()\fR will not return until every session has ended. This includes sessions that were created while \fBrun()\fR was running. .PP POE::Kernel will print a strong message if a program creates sessions but fails to call \fBrun()\fR. Prior to this warning, we received tons of bug reports along the lines of \*(L"my \s-1POE\s0 program isn't doing anything\*(R". It turned out that people forgot to start an event dispatcher, so events were never dispatched. .PP If the lack of a \fBrun()\fR call is deliberate, perhaps because some other event loop already has control, you can avoid the message by calling it before creating a session. \fBrun()\fR at that point will initialize \s-1POE\s0 and return immediately. POE::Kernel will be satisfied that \fBrun()\fR was called, although \s-1POE\s0 will not have actually taken control of the event loop. .PP .Vb 4 \& use POE; \& POE::Kernel\->run(); # silence the warning \& POE::Session\->create( ... ); \& exit; .Ve .PP Note, however, that this varies from one event loop to another. If a particular POE::Loop implementation doesn't support it, that's probably a bug. Please file a bug report with the owner of the relevant POE::Loop module. .PP \fIrun_one_timeslice\fR .IX Subsection "run_one_timeslice" .PP \&\fBrun_one_timeslice()\fR dispatches any events that are due to be delivered. These events include timers that are due, asynchronous messages that need to be delivered, signals that require handling, and notifications for files with pending I/O. Do not rely too much on event ordering. \fBrun_one_timeslice()\fR is defined by the underlying event loop, and its timing may vary. .PP \&\fBrun()\fR is implemented similar to .PP .Vb 1 \& run_one_timeslice() while $session_count > 0; .Ve .PP \&\fBrun_one_timeslice()\fR can be used to keep running POE::Kernel's dispatcher while emulating blocking behavior. The pattern is implemented with a flag that is set when some asynchronous event occurs. A loop calls \fBrun_one_timeslice()\fR until that flag is set. For example: .PP .Vb 1 \& my $done = 0; \& \& sub handle_some_event { \& $done = 1; \& } \& \& $kernel\->run_one_timeslice() while not $done; .Ve .PP Do be careful. The above example will spin if POE::Kernel is done but \&\f(CW$done\fR is never set. The loop will never be done, even though there's nothing left that will set \f(CW$done\fR. .PP \fIrun_while \s-1SCALAR_REF\s0\fR .IX Subsection "run_while SCALAR_REF" .PP \&\fBrun_while()\fR is an \fBexperimental\fR version of \fBrun_one_timeslice()\fR that will only return when there are no more active sessions, or the value of the referenced scalar becomes false. .PP Here's a version of the \fBrun_one_timeslice()\fR example using \fBrun_while()\fR instead: .PP .Vb 1 \& my $job_count = 3; \& \& sub handle_some_event { \& $job_count\-\-; \& } \& \& $kernel\->run_while(\e$job_count); .Ve .PP \fIhas_forked\fR .IX Subsection "has_forked" .PP .Vb 5 \& my $pid = fork(); \& die "Unable to fork" unless defined $pid; \& unless( $pid ) { \& $poe_kernel\->has_forked; \& } .Ve .PP Inform the kernel that it is now running in a new process. This allows the kernel to reset some internal data to adjust to the new situation. .PP \&\fBhas_forked()\fR must be called in the child process if you wish to run the same kernel. However, if you want the child process to have new kernel, you must call \*(L"stop\*(R" instead. .PP \&\fBNote:\fR \s-1POE\s0's internals will detect if a fork occurred before \f(CW\*(C`run()\*(C'\fR and will call \f(CW\*(C`has_forked()\*(C'\fR automatically. If you are unsure whether you need to call it or not, please enable \*(L"\s-1ASSERT_USAGE\*(R"\s0 and \s-1POE\s0 will emit a warning if it's necessary. .PP \fIstop\fR .IX Subsection "stop" .PP \&\fBstop()\fR causes POE::Kernel\->\fBrun()\fR to return early. It does this by emptying the event queue, freeing all used resources, and stopping every active session. \fBstop()\fR is not meant to be used lightly. Proceed with caution. .PP Caveats: .PP The session that calls \fBstop()\fR will not be fully DESTROYed until it returns. Invoking an event handler in the session requires a reference to that session, and weak references are prohibited in \s-1POE\s0 for backward compatibility reasons, so it makes sense that the last session won't be garbage collected right away. .PP Sessions are not notified about their destruction. If anything relies on _stop being delivered, it will break and/or leak memory. .PP \&\fBstop()\fR is still considered experimental. It was added to improve \fBfork()\fR support for POE::Wheel::Run. If it proves unfixably problematic, it will be removed without much notice. .PP \&\fBstop()\fR is advanced magic. Programmers who think they need it are invited to become familiar with its source. .PP See \*(L"Running POE::Kernel in the Child\*(R" in POE::Wheel::Run for an example of how to use this facility. .SS "Asynchronous Messages (\s-1FIFO\s0 Events)" .IX Subsection "Asynchronous Messages (FIFO Events)" Asynchronous messages are events that are dispatched in the order in which they were enqueued (the first one in is the first one out, otherwise known as first\-in/first\-out, or \s-1FIFO\s0 order). These methods enqueue new messages for delivery. The act of enqueuing a message keeps the sender alive at least until the message is delivered. .PP \fIpost \s-1DESTINATION, EVENT_NAME\s0 [, \s-1PARAMETER_LIST\s0]\fR .IX Subsection "post DESTINATION, EVENT_NAME [, PARAMETER_LIST]" .PP \&\fBpost()\fR enqueues a message to be dispatched to a particular \s-1DESTINATION\s0 session. The message will be handled by the code associated with \&\s-1EVENT_NAME.\s0 If a \s-1PARAMETER_LIST\s0 is included, its values will also be passed along. .PP .Vb 11 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[KERNEL]\->post( $_[SESSION], "event_name", 0 ); \& }, \& event_name => sub { \& print "$_[ARG0]\en"; \& $_[KERNEL]\->post( $_[SESSION], "event_name", $_[ARG0] + 1 ); \& }, \& } \& ); .Ve .PP \&\fBpost()\fR returns a Boolean value indicating whether the message was successfully enqueued. If \fBpost()\fR returns false, $! is set to explain the failure: .PP \&\s-1ESRCH\s0 (\*(L"No such process\*(R") \- The \s-1DESTINATION\s0 session did not exist at the time \fBpost()\fR was called. .PP \fIyield \s-1EVENT_NAME\s0 [, \s-1PARAMETER_LIST\s0]\fR .IX Subsection "yield EVENT_NAME [, PARAMETER_LIST]" .PP \&\fByield()\fR is a shortcut for \fBpost()\fR where the destination session is the same as the sender. This example is equivalent to the one for \fBpost()\fR: .PP .Vb 11 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[KERNEL]\->yield( "event_name", 0 ); \& }, \& event_name => sub { \& print "$_[ARG0]\en"; \& $_[KERNEL]\->yield( "event_name", $_[ARG0] + 1 ); \& }, \& } \& ); .Ve .PP As with \fBpost()\fR, \fByield()\fR returns right away, and the enqueued \&\s-1EVENT_NAME\s0 is dispatched later. This may be confusing if you're already familiar with threading. .PP \&\fByield()\fR should always succeed, so it does not return a meaningful value. .SS "Synchronous Messages" .IX Subsection "Synchronous Messages" It is sometimes necessary for code to be invoked right away. For example, some resources must be serviced right away, or they'll faithfully continue reporting their readiness. These reports would appear as a stream of duplicate events. Synchronous events can also prevent data from going stale between the time an event is enqueued and the time it's delivered. .PP Synchronous event handlers preempt \s-1POE\s0's event queue, so they should perform simple tasks of limited duration. Synchronous events that need to do more than just service a resource should pass the resource's information to an asynchronous handler. Otherwise synchronous operations will occur out of order in relation to asynchronous events. It's very easy to have race conditions or break causality this way, so try to avoid it unless you're okay with the consequences. .PP \&\s-1POE\s0 provides these ways to call message handlers right away. .PP \fIcall \s-1DESTINATION, EVENT_NAME\s0 [, \s-1PARAMETER_LIST\s0]\fR .IX Subsection "call DESTINATION, EVENT_NAME [, PARAMETER_LIST]" .PP \&\fBcall()\fR's semantics are nearly identical to \fBpost()\fR's. \fBcall()\fR invokes a \&\s-1DESTINATION\s0's handler associated with an \s-1EVENT_NAME.\s0 An optional \&\s-1PARAMETER_LIST\s0 will be passed along to the message's handler. The difference, however, is that the handler will be invoked immediately, even before \fBcall()\fR returns. .PP \&\fBcall()\fR returns the value returned by the \s-1EVENT_NAME\s0 handler. It can do this because the handler is invoked before \fBcall()\fR returns. \fBcall()\fR can therefore be used as an accessor, although there are better ways to accomplish simple accessor behavior. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& print "Got: ", $_[KERNEL]\->call($_[SESSION], "do_now"), "\en"; \& }, \& do_now => sub { \& return "some value"; \& } \& } \& ); .Ve .PP The POE::Wheel classes uses \fBcall()\fR to synchronously deliver I/O notifications. This avoids a host of race conditions. .PP \&\fBcall()\fR may fail in the same way and for the same reasons as \fBpost()\fR. On failure, $! is set to some nonzero value indicating why. Since \&\fBcall()\fR may return undef as a matter of course, it's recommended that $! be checked for the error condition as well as the explanation. .PP \&\s-1ESRCH\s0 (\*(L"No such process\*(R") \- The \s-1DESTINATION\s0 session did not exist at the time \fBpost()\fR was called. .SS "Timer Events (Delayed Messages)" .IX Subsection "Timer Events (Delayed Messages)" It's often useful to wait for a certain time or until a certain amount of time has passed. \s-1POE\s0 supports this with events that are deferred until either an absolute time (\*(L"alarms\*(R") or until a certain duration of time has elapsed (\*(L"delays\*(R"). .PP Timer interfaces are further divided into two groups. One group identifies timers by the names of their associated events. Another group identifies timers by a unique identifier returned by the timer constructors. Technically, the two are both name-based, but the \*(L"identifier-based\*(R" timers provide a second, more specific handle to identify individual timers. .PP Timers may only be set up for the current session. This design was modeled after \fBalarm()\fR and \s-1SIGALRM,\s0 which only affect the current \s-1UNIX\s0 process. Each session has a separate namespace for timer names. Timer methods called in one session cannot affect the timers in another. As you may have noticed, quite a lot of \s-1POE\s0's \s-1API\s0 is designed to prevent sessions from interfering with each other. .PP The best way to simulate deferred inter-session messages is to send an immediate message that causes the destination to set a timer. The destination's timer then defers the action requested of it. This way is preferred because the time spent communicating the request between sessions may not be trivial, especially if the sessions are separated by a network. The destination can determine how much time remains on the requested timer and adjust its wait time accordingly. .PP \fIName-Based Timers\fR .IX Subsection "Name-Based Timers" .PP Name-based timers are identified by the event names used to set them. It is possible for different sessions to use the same timer event names, since each session is a separate compartment with its own timer namespace. It is possible for a session to have multiple timers for a given event, but results may be surprising. Be careful to use the right timer methods. .PP The name-based timer methods are \fBalarm()\fR, \fBalarm_add()\fR, \fBdelay()\fR, and \&\fBdelay_add()\fR. .PP alarm \s-1EVENT_NAME\s0 [, \s-1EPOCH_TIME\s0 [, \s-1PARAMETER_LIST\s0] ] .IX Subsection "alarm EVENT_NAME [, EPOCH_TIME [, PARAMETER_LIST] ]" .PP \&\fBalarm()\fR clears all existing timers in the current session with the same \s-1EVENT_NAME.\s0 It then sets a new timer, named \s-1EVENT_NAME,\s0 that will fire \s-1EVENT_NAME\s0 at the current session when \s-1EPOCH_TIME\s0 has been reached. An optional \s-1PARAMETER_LIST\s0 may be passed along to the timer's handler. .PP Omitting the \s-1EPOCH_TIME\s0 and subsequent parameters causes \fBalarm()\fR to clear the \s-1EVENT_NAME\s0 timers in the current session without setting a new one. .PP \&\s-1EPOCH_TIME\s0 is the \s-1UNIX\s0 epoch time. You know, seconds since midnight, 1970\-01\-01. \s-1POE\s0 uses \fBTime::HiRes::time()\fR, which allows \s-1EPOCH_TIME\s0 to be (or include) fractional seconds. .PP \&\s-1POE\s0 supports fractional seconds, but accuracy falls off steeply after 1/100 second. Mileage will vary depending on your \s-1CPU\s0 speed and your \&\s-1OS\s0 time resolution. .PP Be sure to use \fBTime::HiRes::time()\fR rather than Perl's built-in \fBtime()\fR if sub-second accuracy matters at all. The built-in \fBtime()\fR returns floor(\fBTime::HiRes::time()\fR), which is nearly always some fraction of a second in the past. For example the high-resolution time might be 1200941422.89996. At that same instant, \fBtime()\fR would be 1200941422. An alarm for \fBtime()\fR + 0.5 would be 0.39996 seconds in the past, so it would be dispatched immediately (if not sooner). .PP \&\s-1POE\s0's event queue is time-ordered, so a timer due before \fBtime()\fR will be delivered ahead of other events but not before timers with even earlier due times. Therefore an \fBalarm()\fR with an \s-1EPOCH_TIME\s0 before \&\fBtime()\fR jumps ahead of the queue. .PP All timers are implemented identically internally, regardless of how they are set. \fBalarm()\fR will therefore blithely clear timers set by other means. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[KERNEL]\->alarm( tick => time() + 1, 0 ); \& }, \& tick => sub { \& print "tick $_[ARG0]\en"; \& $_[KERNEL]\->alarm( tock => time() + 1, $_[ARG0] + 1 ); \& }, \& tock => sub { \& print "tock $_[ARG0]\en"; \& $_[KERNEL]\->alarm( tick => time() + 1, $_[ARG0] + 1 ); \& }, \& } \& ); .Ve .PP \&\fBalarm()\fR returns 0 on success or a true value on failure. Usually \&\s-1EINVAL\s0 to signal an invalid parameter, such as an undefined \&\s-1EVENT_NAME.\s0 .PP alarm_add \s-1EVENT_NAME, EPOCH_TIME\s0 [, \s-1PARAMETER_LIST\s0] .IX Subsection "alarm_add EVENT_NAME, EPOCH_TIME [, PARAMETER_LIST]" .PP \&\fBalarm_add()\fR is used to add a new alarm timer named \s-1EVENT_NAME\s0 without clearing existing timers. \s-1EPOCH_TIME\s0 is a required parameter. Otherwise the semantics are identical to \fBalarm()\fR. .PP A program may use \fBalarm_add()\fR without first using \fBalarm()\fR. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[KERNEL]\->alarm_add( tick => time() + 1.0, 1_000_000 ); \& $_[KERNEL]\->alarm_add( tick => time() + 1.5, 2_000_000 ); \& }, \& tick => sub { \& print "tick $_[ARG0]\en"; \& $_[KERNEL]\->alarm_add( tock => time() + 1, $_[ARG0] + 1 ); \& }, \& tock => sub { \& print "tock $_[ARG0]\en"; \& $_[KERNEL]\->alarm_add( tick => time() + 1, $_[ARG0] + 1 ); \& }, \& } \& ); .Ve .PP \&\fBalarm_add()\fR returns 0 on success or \s-1EINVAL\s0 if \s-1EVENT_NAME\s0 or \s-1EPOCH_TIME\s0 is undefined. .PP delay \s-1EVENT_NAME\s0 [, \s-1DURATION_SECONDS\s0 [, \s-1PARAMETER_LIST\s0] ] .IX Subsection "delay EVENT_NAME [, DURATION_SECONDS [, PARAMETER_LIST] ]" .PP \&\fBdelay()\fR clears all existing timers in the current session with the same \s-1EVENT_NAME.\s0 It then sets a new timer, named \s-1EVENT_NAME,\s0 that will fire \s-1EVENT_NAME\s0 at the current session when \s-1DURATION_SECONDS\s0 have elapsed from \*(L"now\*(R". An optional \s-1PARAMETER_LIST\s0 may be passed along to the timer's handler. .PP Omitting the \s-1DURATION_SECONDS\s0 and subsequent parameters causes \fBdelay()\fR to clear the \s-1EVENT_NAME\s0 timers in the current session without setting a new one. .PP \&\s-1DURATION_SECONDS\s0 may be or include fractional seconds. As with all of \&\s-1POE\s0's timers, accuracy falls off steeply after 1/100 second. Mileage will vary depending on your \s-1CPU\s0 speed and your \s-1OS\s0 time resolution. .PP \&\s-1POE\s0's event queue is time-ordered, so a timer due before \fBtime()\fR will be delivered ahead of other events but not before timers with even earlier due times. Therefore a delay () with a zero or negative \&\s-1DURATION_SECONDS\s0 jumps ahead of the queue. .PP \&\fBdelay()\fR may be considered a shorthand form of \fBalarm()\fR, but there are subtle differences in timing issues. This code is roughly equivalent to the \fBalarm()\fR example. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[KERNEL]\->delay( tick => 1, 0 ); \& }, \& tick => sub { \& print "tick $_[ARG0]\en"; \& $_[KERNEL]\->delay( tock => 1, $_[ARG0] + 1 ); \& }, \& tock => sub { \& print "tock $_[ARG0]\en"; \& $_[KERNEL]\->delay( tick => 1, $_[ARG0] + 1 ); \& }, \& } \& ); .Ve .PP \&\fBdelay()\fR returns 0 on success or a reason for failure: \s-1EINVAL\s0 if \&\s-1EVENT_NAME\s0 is undefined. .PP delay_add \s-1EVENT_NAME, DURATION_SECONDS\s0 [, \s-1PARAMETER_LIST\s0] .IX Subsection "delay_add EVENT_NAME, DURATION_SECONDS [, PARAMETER_LIST]" .PP \&\fBdelay_add()\fR is used to add a new delay timer named \s-1EVENT_NAME\s0 without clearing existing timers. \s-1DURATION_SECONDS\s0 is a required parameter. Otherwise the semantics are identical to \fBdelay()\fR. .PP A program may use \fBdelay_add()\fR without first using \fBdelay()\fR. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[KERNEL]\->delay_add( tick => 1.0, 1_000_000 ); \& $_[KERNEL]\->delay_add( tick => 1.5, 2_000_000 ); \& }, \& tick => sub { \& print "tick $_[ARG0]\en"; \& $_[KERNEL]\->delay_add( tock => 1, $_[ARG0] + 1 ); \& }, \& tock => sub { \& print "tock $_[ARG0]\en"; \& $_[KERNEL]\->delay_add( tick => 1, $_[ARG0] + 1 ); \& }, \& } \& ); .Ve .PP \&\fBdelay_add()\fR returns 0 on success or \s-1EINVAL\s0 if \s-1EVENT_NAME\s0 or \s-1EPOCH_TIME\s0 is undefined. .PP \fIIdentifier-Based Timers\fR .IX Subsection "Identifier-Based Timers" .PP A second way to manage timers is through identifiers. Setting an alarm or delay with the \*(L"identifier\*(R" methods allows a program to manipulate several timers with the same name in the same session. As covered in \fBalarm()\fR and \fBdelay()\fR however, it's possible to mix named and identified timer calls, but the consequences may not always be expected. .PP alarm_set \s-1EVENT_NAME, EPOCH_TIME\s0 [, \s-1PARAMETER_LIST\s0] .IX Subsection "alarm_set EVENT_NAME, EPOCH_TIME [, PARAMETER_LIST]" .PP \&\fBalarm_set()\fR sets an alarm, returning a unique identifier that can be used to adjust or remove the alarm later. Unlike \fBalarm()\fR, it does not first clear existing timers with the same \s-1EVENT_NAME.\s0 Otherwise the semantics are identical to \fBalarm()\fR. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[HEAP]{alarm_id} = $_[KERNEL]\->alarm_set( \& party => time() + 1999 \& ); \& $_[KERNEL]\->delay(raid => 1); \& }, \& raid => sub { \& $_[KERNEL]\->alarm_remove( delete $_[HEAP]{alarm_id} ); \& }, \& } \& ); .Ve .PP \&\fBalarm_set()\fR returns false if it fails and sets $! with the explanation. $! will be \s-1EINVAL\s0 if \s-1EVENT_NAME\s0 or \s-1TIME\s0 is undefined. .PP alarm_adjust \s-1ALARM_ID, DELTA_SECONDS\s0 .IX Subsection "alarm_adjust ALARM_ID, DELTA_SECONDS" .PP \&\fBalarm_adjust()\fR adjusts an existing timer's due time by \s-1DELTA_SECONDS,\s0 which may be positive or negative. It may even be zero, but that's not as useful. On success, it returns the timer's new due time since the start of the \s-1UNIX\s0 epoch. .PP It's possible to \fBalarm_adjust()\fR timers created by \fBdelay_set()\fR as well as \fBalarm_set()\fR. .PP This example moves an alarm's due time ten seconds earlier. .PP .Vb 1 \& use POSIX qw(strftime); \& \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[HEAP]{alarm_id} = $_[KERNEL]\->alarm_set( \& party => time() + 1999 \& ); \& $_[KERNEL]\->delay(postpone => 1); \& }, \& postpone => sub { \& my $new_time = $_[KERNEL]\->alarm_adjust( \& $_[HEAP]{alarm_id}, \-10 \& ); \& print( \& "Now we\*(Aqre gonna party like it\*(Aqs ", \& strftime("%F %T", gmtime($new_time)), "\en" \& ); \& }, \& } \& ); .Ve .PP \&\fBalarm_adjust()\fR returns Boolean false if it fails, setting $! to the reason why. $! may be \s-1EINVAL\s0 if \s-1ALARM_ID\s0 or \s-1DELTA_SECONDS\s0 are undefined. It may be \s-1ESRCH\s0 if \s-1ALARM_ID\s0 no longer refers to a pending timer. $! may also contain \s-1EPERM\s0 if \s-1ALARM_ID\s0 is valid but belongs to a different session. .PP alarm_remove \s-1ALARM_ID\s0 .IX Subsection "alarm_remove ALARM_ID" .PP \&\fBalarm_remove()\fR removes the alarm identified by \s-1ALARM_ID.\s0 \s-1ALARM_ID\s0 comes from a previous \fBalarm_set()\fR or \fBdelay_set()\fR call. .PP Upon success, \fBalarm_remove()\fR returns something true based on its context. In a list context, it returns three things: The removed alarm's event name, the \s-1UNIX\s0 time it was due to go off, and a reference to the \s-1PARAMETER_LIST\s0 (if any) assigned to the timer when it was created. If necessary, the timer can be re-set with this information. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[HEAP]{alarm_id} = $_[KERNEL]\->alarm_set( \& party => time() + 1999 \& ); \& $_[KERNEL]\->delay(raid => 1); \& }, \& raid => sub { \& my ($name, $time, $param) = $_[KERNEL]\->alarm_remove( \& $_[HEAP]{alarm_id} \& ); \& print( \& "Removed alarm for event $name due at $time with @$param\en" \& ); \& \& # Or reset it, if you\*(Aqd like. Possibly after modification. \& $_[KERNEL]\->alarm_set($name, $time, @$param); \& }, \& } \& ); .Ve .PP In a scalar context, it returns a reference to a list of the three things above. .PP .Vb 5 \& # Remove and reset an alarm. \& my $alarm_info = $_[KERNEL]\->alarm_remove( $alarm_id ); \& my $new_id = $_[KERNEL]\->alarm_set( \& $alarm_info[0], $alarm_info[1], @{$alarm_info[2]} \& ); .Ve .PP Upon failure, however, \fBalarm_remove()\fR returns a Boolean false value and sets $! with the reason why the call failed: .PP \&\s-1EINVAL\s0 (\*(L"Invalid argument\*(R") indicates a problem with one or more parameters, usually an undefined \s-1ALARM_ID.\s0 .PP \&\s-1ESRCH\s0 (\*(L"No such process\*(R") indicates that \s-1ALARM_ID\s0 did not refer to a pending alarm. .PP \&\s-1EPERM\s0 (\*(L"Operation not permitted\*(R"). A session cannot remove an alarm it does not own. .PP alarm_remove_all .IX Subsection "alarm_remove_all" .PP \&\fBalarm_remove_all()\fR removes all the pending timers for the current session, regardless of creation method or type. This method takes no arguments. It returns information about the alarms that were removed, either as a list of alarms or a list reference depending whether \&\fBalarm_remove_all()\fR is called in scalar or list context. .PP Each removed alarm's information is identical to the format explained in \fBalarm_remove()\fR. .PP .Vb 7 \& sub some_event_handler { \& my @removed_alarms = $_[KERNEL]\->alarm_remove_all(); \& foreach my $alarm (@removed_alarms) { \& my ($name, $time, $param) = @$alarm; \& ...; \& } \& } .Ve .PP delay_set \s-1EVENT_NAME, DURATION_SECONDS\s0 [, \s-1PARAMETER_LIST\s0] .IX Subsection "delay_set EVENT_NAME, DURATION_SECONDS [, PARAMETER_LIST]" .PP \&\fBdelay_set()\fR sets a timer for \s-1DURATION_SECONDS\s0 in the future. The timer will be dispatched to the code associated with \s-1EVENT_NAME\s0 in the current session. An optional \s-1PARAMETER_LIST\s0 will be passed through to the handler. It returns the same sort of things that \fBalarm_set()\fR does. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[KERNEL]\->delay_set("later", 5, "hello", "world"); \& }, \& later => sub { \& print "@_[ARG0..#$_]\en"; \& } \& } \& ); .Ve .PP delay_adjust \s-1ALARM_ID, SECONDS_FROM_NOW\s0 .IX Subsection "delay_adjust ALARM_ID, SECONDS_FROM_NOW" .PP \&\fBdelay_adjust()\fR changes a timer's due time to be \s-1SECONDS_FROM_NOW.\s0 It's useful for refreshing watchdog\- or timeout-style timers. On success it returns the new absolute \s-1UNIX\s0 time the timer will be due. .PP It's possible for \fBdelay_adjust()\fR to adjust timers created by \&\fBalarm_set()\fR as well as \fBdelay_set()\fR. .PP .Vb 1 \& use POSIX qw(strftime); \& \& POE::Session\->create( \& inline_states => { \& # Setup. \& # ... omitted. \& \& got_input => sub { \& my $new_time = $_[KERNEL]\->delay_adjust( \& $_[HEAP]{input_timeout}, 60 \& ); \& print( \& "Refreshed the input timeout. Next may occur at ", \& strftime("%F %T", gmtime($new_time)), "\en" \& ); \& }, \& } \& ); .Ve .PP On failure it returns Boolean false and sets $! to a reason for the failure. See the explanation of $! for \fBalarm_adjust()\fR. .PP delay_remove is not needed .IX Subsection "delay_remove is not needed" .PP There is no \fBdelay_remove()\fR. Timers are all identical internally, so \&\fBalarm_remove()\fR will work with timer IDs returned by \fBdelay_set()\fR. .PP delay_remove_all is not needed .IX Subsection "delay_remove_all is not needed" .PP There is no \fBdelay_remove_all()\fR. Timers are all identical internally, so \fBalarm_remove_all()\fR clears them all regardless how they were created. .PP \fIComparison\fR .IX Subsection "Comparison" .PP Below is a table to help compare the various delayed message-sending methods .PP .Vb 9 \& +\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+ \& | | time argument | clears other events | returns on | \& | method | passed to method | of the same name | success | \& +\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+ \& | delay_set | seconds from now | N | alarm_id | \& | delay | seconds from now | Y | 0 (false) | \& | alarm_set | unix epoch time | N | alarm_id | \& | alarm | unix epoch time | Y | 0 (false) | \& +\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+ .Ve .SS "Session Identifiers (IDs and Aliases)" .IX Subsection "Session Identifiers (IDs and Aliases)" A session may be referred to by its object references (either blessed or stringified), a session \s-1ID,\s0 or one or more symbolic names we call aliases. .PP Every session is represented by an object, so session references are fairly straightforward. POE::Kernel may reference these objects. For instance, \fBpost()\fR may use \f(CW$_\fR[\s-1SENDER\s0] as a destination: .PP .Vb 8 \& POE::Session\->create( \& inline_states => { \& _start => sub { $_[KERNEL]\->alias_set("echoer") }, \& ping => sub { \& $_[KERNEL]\->post( $_[SENDER], "pong", @_[ARG0..$#_] ); \& } \& } \& ); .Ve .PP \&\s-1POE\s0 also recognized stringified Session objects for convenience and as a form of weak reference. Here \f(CW$_\fR[\s-1SENDER\s0] is wrapped in quotes to stringify it: .PP .Vb 8 \& POE::Session\->create( \& inline_states => { \& _start => sub { $_[KERNEL]\->alias_set("echoer") }, \& ping => sub { \& $_[KERNEL]\->post( "$_[SENDER]", "pong", @_[ARG0..$#_] ); \& } \& } \& ); .Ve .PP Every session is assigned a unique \s-1ID\s0 at creation time. No two active sessions will have the same \s-1ID,\s0 but IDs may be reused over time. The combination of a kernel \s-1ID\s0 and a session \s-1ID\s0 should be sufficient as a global unique identifier. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { $_[KERNEL]\->alias_set("echoer") }, \& ping => sub { \& $_[KERNEL]\->delay( \& pong_later => rand(5), $_[SENDER]\->ID, @_[ARG0..$#_] \& ); \& }, \& pong_later => sub { \& $_[KERNEL]\->post( $_[ARG0], "pong", @_[ARG1..$#_] ); \& } \& } \& ); .Ve .PP Kernels also maintain a global session namespace or dictionary from which may be used to map a symbolic aliases to a session. Once an alias is mapping has been created, that alias may be used to refer to the session wherever a session may be specified. .PP In the previous examples, each echoer service has set an \*(L"echoer\*(R" alias. Another session can post a ping request to the echoer session by using that alias rather than a session object or \s-1ID.\s0 For example: .PP .Vb 6 \& POE::Session\->create( \& inline_states => { \& _start => sub { $_[KERNEL]\->post(echoer => ping => "whee!" ) }, \& pong => sub { print "@_[ARG0..$#_]\en" } \& } \& ); .Ve .PP A session with an alias will not stop until all other activity has stopped. Aliases are treated as a kind of event watcher. Events come from active sessions. Aliases therefore become useless when there are no active sessions left. Rather than leaving the program running in a \*(L"zombie\*(R" state, \&\s-1POE\s0 detects this deadlock condition and triggers a cleanup. See \&\*(L"Signal Classes\*(R" for more information. .PP \fIalias_set \s-1ALIAS\s0\fR .IX Subsection "alias_set ALIAS" .PP \&\fBalias_set()\fR maps an \s-1ALIAS\s0 in POE::Kernel's dictionary to the current session. The \s-1ALIAS\s0 may then be used nearly everywhere a session reference, stringified reference, or \s-1ID\s0 is expected. .PP Sessions may have more than one alias. Each alias must be defined in a separate \fBalias_set()\fR call. A single alias may not refer to more than one session. .PP Multiple alias examples are above. .PP \&\fBalias_set()\fR returns 0 on success, or a nonzero failure indicator: \&\s-1EEXIST\s0 (\*(L"File exists\*(R") indicates that the alias is already assigned to to a different session. .PP \fIalias_remove \s-1ALIAS\s0\fR .IX Subsection "alias_remove ALIAS" .PP \&\fBalias_remove()\fR removes an \s-1ALIAS\s0 for the current session from POE::Kernel's dictionary. The \s-1ALIAS\s0 will no longer refer to the current session. This does not negatively affect events already posted to \s-1POE\s0's queue. Alias resolution occurs at \fBpost()\fR time, not at delivery time. .PP .Vb 11 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[KERNEL]\->alias_set("short_window"); \& $_[KERNEL]\->delay(close_window => 1); \& }, \& close_window => { \& $_[KERNEL]\->alias_remove("short_window"); \& } \& } \& ); .Ve .PP \&\fBalias_remove()\fR returns 0 on success or a nonzero failure code: \s-1ESRCH\s0 (\*(L"No such process\*(R") indicates that the \s-1ALIAS\s0 is not currently in POE::Kernel's dictionary. \s-1EPERM\s0 (\*(L"Operation not permitted\*(R") means that the current session may not remove the \s-1ALIAS\s0 because it is in use by some other session. .PP \fIalias_resolve \s-1ALIAS\s0\fR .IX Subsection "alias_resolve ALIAS" .PP \&\fBalias_resolve()\fR returns a session reference corresponding to a given \&\s-1ALIAS.\s0 Actually, the \s-1ALIAS\s0 may be a stringified session reference, a session \s-1ID,\s0 or an alias previously registered by \fBalias_set()\fR. .PP One use for \fBalias_resolve()\fR is to detect whether another session has gone away: .PP .Vb 3 \& unless (defined $_[KERNEL]\->alias_resolve("Elvis")) { \& print "Elvis has left the building.\en"; \& } .Ve .PP As previously mentioned, \fBalias_resolve()\fR returns a session reference or undef on failure. Failure also sets $! to \s-1ESRCH\s0 (\*(L"No such process\*(R") when the \s-1ALIAS\s0 is not currently in POE::Kernel's. .PP \fIalias_list [\s-1SESSION_REFERENCE\s0]\fR .IX Subsection "alias_list [SESSION_REFERENCE]" .PP \&\fBalias_list()\fR returns a list of aliases associated with a specific \&\s-1SESSION,\s0 or with the current session if \s-1SESSION\s0 is omitted. \&\fBalias_list()\fR returns an empty list if the requested \s-1SESSION\s0 has no aliases. .PP \&\s-1SESSION\s0 may be a session reference (blessed or stringified), a session \&\s-1ID,\s0 or a session alias. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& $_[KERNEL]\->alias_set("mi"); \& print( \& "The names I call myself: ", \& join(", ", $_[KERNEL]\->alias_list()), \& "\en" \& ); \& } \& ); .Ve .PP \fIID_id_to_session \s-1SESSION_ID\s0\fR .IX Subsection "ID_id_to_session SESSION_ID" .PP \&\fBID_id_to_session()\fR translates a session \s-1ID\s0 into a session reference. It's a special-purpose subset of \fBalias_resolve()\fR, so it's a little faster and somewhat less flexible. .PP .Vb 3 \& unless (defined $_[KERNEL]\->ID_id_to_session($session_id)) { \& print "Session $session_id doesn\*(Aqt exist.\en"; \& } .Ve .PP \&\fBID_id_to_session()\fR returns undef if a lookup failed. $! will be set to \s-1ESRCH\s0 (\*(L"No such process\*(R"). .PP \fIID_session_to_id \s-1SESSION_REFERENCE\s0\fR .IX Subsection "ID_session_to_id SESSION_REFERENCE" .PP \&\fBID_session_to_id()\fR converts a blessed or stringified \s-1SESSION_REFERENCE\s0 into a session \s-1ID.\s0 It's more practical for stringified references, as programs can call the POE::Session \s-1\fBID\s0()\fR method on the blessed ones. These statements are equivalent: .PP .Vb 3 \& $id = $_[SENDER]\->ID(); \& $id = $_[KERNEL]\->ID_session_to_id($_[SENDER]); \& $id = $_[KERNEL]\->ID_session_to_id("$_[SENDER]"); .Ve .PP As with other POE::Kernel lookup methods, \fBID_session_to_id()\fR returns undef on failure, setting $! to \s-1ESRCH\s0 (\*(L"No such process\*(R"). .SS "I/O Watchers (Selects)" .IX Subsection "I/O Watchers (Selects)" No event system would be complete without the ability to asynchronously watch for I/O events. POE::Kernel implements the lowest level watchers, which are called \*(L"selects\*(R" because they were historically implemented using Perl's built-in \fBselect\fR\|(2) function. .PP Applications handle I/O readiness events by performing some activity on the underlying filehandle. Read-readiness might be handled by reading from the handle. Write-readiness by writing to it. .PP All I/O watcher events include two parameters. \f(CW\*(C`ARG0\*(C'\fR contains the handle that is ready for work. \f(CW\*(C`ARG1\*(C'\fR contains an integer describing what's ready. .PP .Vb 10 \& sub handle_io { \& my ($handle, $mode) = @_[ARG0, ARG1]; \& print "File $handle is ready for "; \& if ($mode == 0) { \& print "reading"; \& } \& elsif ($mode == 1) { \& print "writing"; \& } \& elsif ($mode == 2) { \& print "out\-of\-band reading"; \& } \& else { \& die "unknown mode $mode"; \& } \& print "\en"; \& # ... do something here \& } .Ve .PP The remaining parameters, \f(CW@_[ARG2..$%_]\fR, contain additional parameters that were passed to the POE::Kernel method that created the watcher. .PP POE::Kernel conditions filehandles to be 8\-bit clean and non-blocking. Programs that need them conditioned differently should set them up after starting \s-1POE I/O\s0 watchers. If you are running a Perl older than 5.8.1 and is using tied filehandles, you need to set non-blocking mode yourself as IO::Handle does not work well. See for more info. .PP I/O watchers will prevent sessions from stopping. .PP \fIselect_read \s-1FILE_HANDLE\s0 [, \s-1EVENT_NAME\s0 [, \s-1ADDITIONAL_PARAMETERS\s0] ]\fR .IX Subsection "select_read FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]" .PP \&\fBselect_read()\fR starts or stops the current session from watching for incoming data on a given \s-1FILE_HANDLE.\s0 The watcher is started if \&\s-1EVENT_NAME\s0 is specified, or stopped if it's not. \&\s-1ADDITIONAL_PARAMETERS,\s0 if specified, will be passed to the \s-1EVENT_NAME\s0 handler as \f(CW@_[ARG2..$#_]\fR. .PP .Vb 10 \& POE::Session\->create( \& inline_states => { \& _start => sub { \& $_[HEAP]{socket} = IO::Socket::INET\->new( \& PeerAddr => "localhost", \& PeerPort => 25, \& ); \& $_[KERNEL]\->select_read( $_[HEAP]{socket}, "got_input" ); \& $_[KERNEL]\->delay(timed_out => 1); \& }, \& got_input => sub { \& my $socket = $_[ARG0]; \& while (sysread($socket, my $buf = "", 8192)) { \& print $buf; \& } \& }, \& timed_out => sub { \& $_[KERNEL]\->select_read( delete $_[HEAP]{socket} ); \& }, \& } \& ); .Ve .PP \&\fBselect_read()\fR does not return anything significant. .PP \fIselect_write \s-1FILE_HANDLE\s0 [, \s-1EVENT_NAME\s0 [, \s-1ADDITIONAL_PARAMETERS\s0] ]\fR .IX Subsection "select_write FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]" .PP \&\fBselect_write()\fR follows the same semantics as \fBselect_read()\fR, but it starts or stops a watcher that looks for write-readiness. That is, when \s-1EVENT_NAME\s0 is delivered, it means that \s-1FILE_HANDLE\s0 is ready to be written to. .PP \&\fBselect_write()\fR does not return anything significant. .PP \fIselect_expedite \s-1FILE_HANDLE\s0 [, \s-1EVENT_NAME\s0 [, \s-1ADDITIONAL_PARAMETERS\s0] ]\fR .IX Subsection "select_expedite FILE_HANDLE [, EVENT_NAME [, ADDITIONAL_PARAMETERS] ]" .PP \&\fBselect_expedite()\fR does the same sort of thing as \fBselect_read()\fR and \&\fBselect_write()\fR, but it watches a \s-1FILE_HANDLE\s0 for out-of-band data ready to be input from a \s-1FILE_HANDLE.\s0 Hardly anybody uses this, but it exists for completeness' sake. .PP An \s-1EVENT_NAME\s0 event will be delivered whenever the \s-1FILE_HANDLE\s0 can be read from out-of-band. Out-of-band data is considered \*(L"expedited\*(R" because it is often ahead of a socket's normal data. .PP \&\fBselect_expedite()\fR does not return anything significant. .PP \fIselect_pause_read \s-1FILE_HANDLE\s0\fR .IX Subsection "select_pause_read FILE_HANDLE" .PP \&\fBselect_pause_read()\fR is a lightweight way to pause a \s-1FILE_HANDLE\s0 input watcher without performing all the bookkeeping of a \fBselect_read()\fR. It's used with \fBselect_resume_read()\fR to implement input flow control. .PP Input that occurs on \s-1FILE_HANDLE\s0 will backlog in the operating system buffers until \fBselect_resume_read()\fR is called. .PP A side effect of bypassing the \fBselect_read()\fR bookkeeping is that a paused \s-1FILE_HANDLE\s0 will not prematurely stop the current session. .PP \&\fBselect_pause_read()\fR does not return anything significant. .PP \fIselect_resume_read \s-1FILE_HANDLE\s0\fR .IX Subsection "select_resume_read FILE_HANDLE" .PP \&\fBselect_resume_read()\fR resumes a \s-1FILE_HANDLE\s0 input watcher that was previously paused by \fBselect_pause_read()\fR. See \fBselect_pause_read()\fR for more discussion on lightweight input flow control. .PP Data backlogged in the operating system due to a \fBselect_pause_read()\fR call will become available after \fBselect_resume_read()\fR is called. .PP \&\fBselect_resume_read()\fR does not return anything significant. .PP \fIselect_pause_write \s-1FILE_HANDLE\s0\fR .IX Subsection "select_pause_write FILE_HANDLE" .PP \&\fBselect_pause_write()\fR pauses a \s-1FILE_HANDLE\s0 output watcher the same way \&\fBselect_pause_read()\fR does for input. Please see \fBselect_pause_read()\fR for further discussion. .PP \fIselect_resume_write \s-1FILE_HANDLE\s0\fR .IX Subsection "select_resume_write FILE_HANDLE" .PP \&\fBselect_resume_write()\fR resumes a \s-1FILE_HANDLE\s0 output watcher the same way that \fBselect_resume_read()\fR does for input. See \&\fBselect_resume_read()\fR for further discussion. .PP \fIselect \s-1FILE_HANDLE\s0 [, \s-1EV_READ\s0 [, \s-1EV_WRITE\s0 [, \s-1EV_EXPEDITE\s0 [, \s-1ARGS\s0] ] ] ]\fR .IX Subsection "select FILE_HANDLE [, EV_READ [, EV_WRITE [, EV_EXPEDITE [, ARGS] ] ] ]" .PP POE::Kernel's \fBselect()\fR method sets or clears a \s-1FILE_HANDLE\s0's read, write and expedite watchers at once. It's a little more expensive than calling \fBselect_read()\fR, \fBselect_write()\fR and \fBselect_expedite()\fR manually, but it's significantly more convenient. .PP Defined event names enable their corresponding watchers, and undefined event names disable them. This turns off all the watchers for a \&\s-1FILE_HANDLE:\s0 .PP .Vb 3 \& sub stop_io { \& $_[KERNEL]\->select( $_[HEAP]{file_handle} ); \& } .Ve .PP This statement: .PP .Vb 1 \& $_[KERNEL]\->select( $file_handle, undef, "write_event", undef, @stuff ); .Ve .PP is equivalent to: .PP .Vb 3 \& $_[KERNEL]\->select_read( $file_handle ); \& $_[KERNEL]\->select_write( $file_handle, "write_event", @stuff ); \& $_[KERNEL]\->select_expedite( $file_handle ); .Ve .PP POE::Kernel's \fBselect()\fR should not be confused with Perl's built-in \&\fBselect()\fR function. .PP As with the other I/O watcher methods, \fBselect()\fR does not return a meaningful value. .SS "Session Management" .IX Subsection "Session Management" Sessions are dynamic. They may be created and destroyed during a program's lifespan. When a session is created, it becomes the \*(L"child\*(R" of the current session. The creator \*(-- the current session \*(-- becomes its \*(L"parent\*(R" session. This is loosely modeled after \s-1UNIX\s0 processes. .PP The most common session management is done by creating new sessions and allowing them to eventually stop. .PP Every session has a parent, even the very first session created. Sessions without obvious parents are children of the program's POE::Kernel instance. .PP Child sessions will keep their parents active. See \*(L"Session Lifespans\*(R" for more about why sessions stay alive. .PP The parent/child relationship tree also governs the way many signals are dispatched. See \*(L"Common Signal Dispatching\*(R" for more information on that. .PP \fISession Management Events (_start, _stop, _parent, _child)\fR .IX Subsection "Session Management Events (_start, _stop, _parent, _child)" .PP POE::Kernel provides four session management events: _start, _stop, _parent and _child. They are invoked synchronously whenever a session is newly created or just about to be destroyed. .IP "_start" 2 .IX Item "_start" _start should be familiar by now. \s-1POE\s0 dispatches the _start event to initialize a session after it has been registered under POE::Kernel. What is not readily apparent, however, is that it is invoked before the POE::Session constructor returns. .Sp Within the _start handler, the event's sender is the session that created the new session. Otherwise known as the new session's \&\fIparent\fR. Sessions created before POE::Kernel\->\fBrun()\fR is called will be descendents of the program's POE::Kernel singleton. .Sp The _start handler's return value is passed to the parent session in a _child event, along with the notification that the parent's new child was created successfully. See the discussion of _child for more details. .Sp .Vb 4 \& POE::Session\->create( \& inline_states => { _start=> \e&_start }, \& args => [ $some, $args ] \& ); \& \& sub _start { \& my ( $some, $args ) = @_[ ARG0, ARG1 ]; \& # .... \& } .Ve .IP "_stop" 2 .IX Item "_stop" _stop is a little more mysterious. \s-1POE\s0 calls a _stop handler when a session is irrevocably about to be destroyed. Part of session destruction is the forcible reclamation of its resources (events, timers, message events, etc.) so it's not possible to \fBpost()\fR a message from _stop's handler. A program is free to try, but the event will be destroyed before it has a chance to be dispatched. .Sp the _stop handler's return value is passed to the parent's _child event. See _child for more details. .Sp _stop is usually invoked when a session has no further reason to live, although signals may cause them to stop sooner. .Sp The corresponding _child handler is invoked synchronously just after _stop returns. .IP "_parent" 2 .IX Item "_parent" _parent is used to notify a child session when its parent has changed. This usually happens when a session is first created. It can also happen when a child session is detached from its parent. See detach_child and \*(L"detach_myself\*(R". .Sp _parent's \s-1ARG0\s0 contains the session's previous parent, and \s-1ARG1\s0 contains its new parent. .Sp .Vb 9 \& sub _parent { \& my ( $old_parent, $new_parent ) = @_[ ARG0, ARG1 ]; \& print( \& "Session ", $_[SESSION]\->ID, \& " parent changed from session ", $old_parent\->ID, \& " to session ", $new_parent\->ID, \& "\en" \& ); \& } .Ve .IP "_child" 2 .IX Item "_child" _child notifies one session when a child session has been created, destroyed, or reassigned to or from another parent. It's usually dispatched when sessions are created or destroyed. It can also happen when a session is detached from its parent. .Sp _child includes some information in the \*(L"arguments\*(R" portion of \f(CW@_\fR. Typically \s-1ARG0, ARG1\s0 and \s-1ARG2,\s0 but these may be overridden by a different POE::Session class: .Sp \&\s-1ARG0\s0 contains a string describing what has happened to the child. The string may be 'create' (the child session has been created), 'gain' (the child has been given by another session), or 'lose' (the child session has stopped or been given away). .Sp In all cases, \s-1ARG1\s0 contains a reference to the child session. .Sp In the 'create' case, \s-1ARG2\s0 holds the value returned by the child session's _start handler. Likewise, \s-1ARG2\s0 holds the _stop handler's return value for the 'lose' case. .Sp .Vb 7 \& sub _child { \& my( $reason, $child ) = @_[ ARG0, ARG1 ]; \& if( $reason eq \*(Aqcreate\*(Aq ) { \& my $retval = $_[ ARG2 ]; \& } \& # ... \& } .Ve .PP The events are delivered in specific orders. .PP When a new session is created: .IX Subsection "When a new session is created:" .IP "1." 4 The session's constructor is called. .IP "2." 4 The session is put into play. That is, POE::Kernel enters the session into its bookkeeping. .IP "3." 4 The new session receives _start. .IP "4." 4 The parent session receives _child ('create'), the new session reference, and the new session's _start's return value. .IP "5." 4 The session's constructor returns. .PP When an old session stops: .IX Subsection "When an old session stops:" .IP "1." 4 If the session has children of its own, they are given to the session's parent. This triggers one or more _child ('gain') events in the parent, and a _parent in each child. .IP "2." 4 Once divested of its children, the stopping session receives a _stop event. .IP "3." 4 The stopped session's parent receives a _child ('lose') event with the departing child's reference and _stop handler's return value. .IP "4." 4 The stopped session is removed from play, as are all its remaining resources. .IP "5." 4 The parent session is checked for idleness. If so, garbage collection will commence on it, and it too will be stopped .PP When a session is detached from its parent: .IX Subsection "When a session is detached from its parent:" .IP "1." 4 The parent session of the session being detached is notified with a _child ('lose') event. The _stop handler's return value is undef since the child is not actually stopping. .IP "2." 4 The detached session is notified with a _parent event that its new parent is POE::Kernel itself. .IP "3." 4 POE::Kernel's bookkeeping data is adjusted to reflect the change of parentage. .IP "4." 4 The old parent session is checked for idleness. If so, garbage collection will commence on it, and it too will be stopped .PP \fISession Management Methods\fR .IX Subsection "Session Management Methods" .PP These methods allow sessions to be detached from their parents in the rare cases where the parent/child relationship gets in the way. .PP detach_child \s-1CHILD_SESSION\s0 .IX Subsection "detach_child CHILD_SESSION" .PP \&\fBdetach_child()\fR detaches a particular \s-1CHILD_SESSION\s0 from the current session. On success, the \s-1CHILD_SESSION\s0 will become a child of the POE::Kernel instance, and \fBdetach_child()\fR will return true. On failure however, \fBdetach_child()\fR returns false and sets $! to explain the nature of the failure: .ie n .IP "\s-1ESRCH\s0 (""No such process"")." 4 .el .IP "\s-1ESRCH\s0 (``No such process'')." 4 .IX Item "ESRCH (No such process)." The \s-1CHILD_SESSION\s0 is not a valid session. .ie n .IP "\s-1EPERM\s0 (""Operation not permitted"")." 4 .el .IP "\s-1EPERM\s0 (``Operation not permitted'')." 4 .IX Item "EPERM (Operation not permitted)." The \s-1CHILD_SESSION\s0 exists, but it is not a child of the current session. .PP \&\fBdetach_child()\fR will generate \*(L"_parent\*(R" and/or \*(L"_child\*(R" events to the appropriate sessions. See Session Management Events for a detailed explanation of these events. See above for the order the events are generated. .PP detach_myself .IX Subsection "detach_myself" .PP \&\fBdetach_myself()\fR detaches the current session from its current parent. The new parent will be the running POE::Kernel instance. It returns true on success. On failure it returns false and sets \f(CW$!\fR to explain the nature of the failure: .ie n .IP "\s-1EPERM\s0 (""Operation not permitted"")." 4 .el .IP "\s-1EPERM\s0 (``Operation not permitted'')." 4 .IX Item "EPERM (Operation not permitted)." The current session is already a child of POE::Kernel, so it may not be detached. .PP \&\fBdetach_child()\fR will generate \*(L"_parent\*(R" and/or \*(L"_child\*(R" events to the appropriate sessions. See Session Management Events for a detailed explanation of these events. See above for the order the events are generated. .SS "Signals" .IX Subsection "Signals" POE::Kernel provides methods through which a program can register interest in signals that come along, can deliver its own signals without resorting to system calls, and can indicate that signals have been handled so that default behaviors are not necessary. .PP Signals are \fIaction at a distance\fR by nature, and their implementation requires widespread synchronization between sessions (and reentrancy in the dispatcher, but that's an implementation detail). Perfecting the semantics has proven difficult, but \s-1POE\s0 tries to do the Right Thing whenever possible. .PP \&\s-1POE\s0 does not register \f(CW%SIG\fR handlers for signals until \fBsig()\fR is called to watch for them. Therefore a signal's default behavior occurs for unhandled signals. That is, \s-1SIGINT\s0 will gracelessly stop a program, \&\s-1SIGWINCH\s0 will do nothing, \s-1SIGTSTP\s0 will pause a program, and so on. .PP \fISignal Classes\fR .IX Subsection "Signal Classes" .PP There are three signal classes. Each class defines a default behavior for the signal and whether the default can be overridden. They are: .PP Benign, advisory, or informative signals .IX Subsection "Benign, advisory, or informative signals" .PP These are three names for the same signal class. Signals in this class notify a session of an event but do not terminate the session if they are not handled. .PP It is possible for an application to create its own benign signals. See \&\*(L"signal\*(R" below. .PP Terminal signals .IX Subsection "Terminal signals" .PP Terminal signals will kill sessions if they are not handled by a \&\*(L"sig_handled\*(R"() call. The \s-1OS\s0 signals that usually kill or dump a process are considered terminal in \s-1POE,\s0 but they never trigger a coredump. These are: \s-1HUP, INT, QUIT\s0 and \s-1TERM.\s0 .PP There are two terminal signals created by and used within \s-1POE:\s0 .IP "\s-1DIE\s0" 4 .IX Item "DIE" \&\f(CW\*(C`DIE\*(C'\fR notifies sessions that a Perl exception has occurred. See \&\*(L"Exception Handling\*(R" for details. .IP "\s-1IDLE\s0" 4 .IX Item "IDLE" The \f(CW\*(C`IDLE\*(C'\fR signal is used to notify leftover sessions that a program has run out of things to do. .PP Nonmaskable signals .IX Subsection "Nonmaskable signals" .PP Nonmaskable signals are terminal regardless whether \fBsig_handled()\fR is called. The term comes from \*(L"\s-1NMI\*(R",\s0 the non-maskable \s-1CPU\s0 interrupt usually generated by an unrecoverable hardware exception. .PP Sessions that receive a non-maskable signal will unavoidably stop. \s-1POE\s0 implements two non-maskable signals: .IP "\s-1ZOMBIE\s0" 4 .IX Item "ZOMBIE" This non-maskable signal is fired if a program has received an \f(CW\*(C`IDLE\*(C'\fR signal but neither restarted nor exited. The program has become a zombie (that is, it's neither dead nor alive, and only exists to consume braaaains ...er... memory). The \f(CW\*(C`ZOMBIE\*(C'\fR signal acts like a cricket bat to the head, bringing the zombie down, for good. .IP "\s-1UIDESTROY\s0" 4 .IX Item "UIDESTROY" This non-maskable signal indicates that a program's user interface has been closed, and the program should take the user's hint and buzz off as well. It's usually generated when a particular \s-1GUI\s0 widget is closed. .PP \fICommon Signal Dispatching\fR .IX Subsection "Common Signal Dispatching" .PP Most signals are not dispatched to a single session. \s-1POE\s0's session lineage (parents and children) form a sort of family tree. When a signal is sent to a session, it first passes through any children (and grandchildren, and so on) that are also interested in the signal. .PP In the case of terminal signals, if any of the sessions a signal passes through calls \*(L"sig_handled\*(R"(), then the signal is considered taken care of. However if none of them do, then the entire session tree rooted at the destination session is terminated. For example, consider this tree of sessions: .PP .Vb 7 \& POE::Kernel \& Session 2 \& Session 4 \& Session 5 \& Session 3 \& Session 6 \& Session 7 .Ve .PP POE::Kernel is the parent of sessions 2 and 3. Session 2 is the parent of sessions 4 and 5. And session 3 is the parent of 6 and 7. .PP A signal sent to Session 2 may also be dispatched to session 4 and 5 because they are 2's children. Sessions 4 and 5 will only receive the signal if they have registered the appropriate watcher. If the signal is terminal, and none of the signal watchers in sessions 2, 4 and 5 called \&\f(CW\*(C`sig_handled()\*(C'\fR, all 3 sessions will be terminated. .PP The program's POE::Kernel instance is considered to be a session for the purpose of signal dispatch. So any signal sent to POE::Kernel will propagate through every interested session in the entire program. This is in fact how \s-1OS\s0 signals are handled: A global signal handler is registered to forward the signal to POE::Kernel. .PP \fISignal Semantics\fR .IX Subsection "Signal Semantics" .PP All signals come with the signal name in \s-1ARG0.\s0 The signal name is as it appears in \f(CW%SIG\fR, with one exception: Child process signals are always \*(L"\s-1CHLD\*(R"\s0 even if the current operating system recognizes them as \&\*(L"\s-1CLD\*(R".\s0 .PP Certain signals have special semantics: .PP \s-1SIGCHLD\s0 .IX Subsection "SIGCHLD" .PP \s-1SIGCLD\s0 .IX Subsection "SIGCLD" .PP Both \f(CW\*(C`SIGCHLD\*(C'\fR and \f(CW\*(C`SIGCLD\*(C'\fR indicate that a child process has exited or been terminated by some signal. The actual signal name varies between operating systems, but \s-1POE\s0 uses \f(CW\*(C`CHLD\*(C'\fR regardless. .PP Interest in \f(CW\*(C`SIGCHLD\*(C'\fR is registered using the \*(L"sig_child\*(R" method. The \*(L"sig\*(R"() method also works, but it's not as nice. .PP The \f(CW\*(C`SIGCHLD\*(C'\fR event includes three parameters: .IP "\s-1ARG0\s0" 4 .IX Item "ARG0" \&\f(CW\*(C`ARG0\*(C'\fR contains the string '\s-1CHLD\s0' (even if the \s-1OS\s0 calls it \s-1SIGCLD, SIGMONKEY,\s0 or something else). .IP "\s-1ARG1\s0" 4 .IX Item "ARG1" \&\f(CW\*(C`ARG1\*(C'\fR contains the process \s-1ID\s0 of the finished child process. .IP "\s-1ARG2\s0" 4 .IX Item "ARG2" And \f(CW\*(C`ARG2\*(C'\fR holds the value of \f(CW$?\fR for the finished process. .PP Example: .PP .Vb 4 \& sub sig_CHLD { \& my( $name, $PID, $exit_val ) = @_[ ARG0, ARG1, ARG2 ]; \& # ... \& } .Ve .PP \s-1SIGPIPE\s0 .IX Subsection "SIGPIPE" .PP \&\s-1SIGPIPE\s0 is rarely used since \s-1POE\s0 provides events that do the same thing. Nevertheless \s-1SIGPIPE\s0 is supported if you need it. Unlike most events, however, \s-1SIGPIPE\s0 is dispatched directly to the active session when it's caught. Barring race conditions, the active session should be the one that caused the \s-1OS\s0 to send the signal in the first place. .PP The \s-1SIGPIPE\s0 signal will still propagate to child sessions. .PP \&\s-1ARG0\s0 is \*(L"\s-1PIPE\*(R".\s0 There is no other information associated with this signal. .PP \s-1SIGWINCH\s0 .IX Subsection "SIGWINCH" .PP Window resizes can generate a large number of signals very quickly. This may not be a problem when using perl 5.8.0 or later, but earlier versions may not take kindly to such abuse. You have been warned. .PP \&\s-1ARG0\s0 is \*(L"\s-1WINCH\*(R".\s0 There is no other information associated with this signal. .PP \fIException Handling\fR .IX Subsection "Exception Handling" .PP POE::Kernel provides only one form of exception handling: the \&\f(CW\*(C`DIE\*(C'\fR signal. .PP When exception handling is enabled (the default), POE::Kernel wraps state invocation in \f(CW\*(C`eval{}\*(C'\fR. If the event handler raises an exception, generally with \f(CW\*(C`die\*(C'\fR, POE::Kernel will dispatch a \f(CW\*(C`DIE\*(C'\fR signal to the event's destination session. .PP \&\f(CW\*(C`ARG0\*(C'\fR is the signal name, \f(CW\*(C`DIE\*(C'\fR. .PP \&\f(CW\*(C`ARG1\*(C'\fR is a hashref describing the exception: .IP "error_str" 4 .IX Item "error_str" The text of the exception. In other words, \f(CW$@\fR. .IP "dest_session" 4 .IX Item "dest_session" Session object of the state that the raised the exception. In other words, \&\f(CW$_[SESSION]\fR in the function that died. .IP "event" 4 .IX Item "event" Name of the event that died. .IP "source_session" 4 .IX Item "source_session" Session object that sent the original event. That is, \f(CW$_[SENDER]\fR in the function that died. .IP "from_state" 4 .IX Item "from_state" State from which the original event was sent. That is, \f(CW$_[CALLER_STATE]\fR in the function that died. .IP "file" 4 .IX Item "file" Name of the file the event was sent from. That is, \f(CW$_[CALLER_FILE]\fR in the function that died. .IP "line" 4 .IX Item "line" Line number the event was sent from. That is, \f(CW$_[CALLER_LINE]\fR in the function that died. .PP \&\fINote that the preceding discussion assumes you are using POE::Session's call semantics.\fR .PP Note that the \f(CW\*(C`DIE\*(C'\fR signal is sent to the session that raised the exception, not the session that sent the event that caused the exception to be raised. .PP .Vb 4 \& sub _start { \& $poe_kernel\->sig( DIE => \*(Aqsig_DIE\*(Aq ); \& $poe_kernel\->yield( \*(Aqsome_event\*(Aq ); \& } \& \& sub some_event { \& die "I didn\*(Aqt like that!"; \& } \& \& sub sig_DIE { \& my( $sig, $ex ) = @_[ ARG0, ARG1 ]; \& # $sig is \*(AqDIE\*(Aq \& # $ex is the exception hash \& warn "$$: error in $ex\->{event}: $ex\->{error_str}"; \& $poe_kernel\->sig_handled(); \& \& # Send the signal to session that sent the original event. \& if( $ex\->{source_session} ne $_[SESSION] ) { \& $poe_kernel\->signal( $ex\->{source_session}, \*(AqDIE\*(Aq, $sig, $ex ); \& } \& } .Ve .PP POE::Kernel's built-in exception handling can be disabled by setting the \f(CW\*(C`POE::Kernel::CATCH_EXCEPTIONS\*(C'\fR constant to zero. As with other compile-time configuration constants, it must be set before POE::Kernel is compiled: .PP .Vb 5 \& BEGIN { \& package POE::Kernel; \& use constant CATCH_EXCEPTIONS => 0; \& } \& use POE; .Ve .PP or .PP .Vb 2 \& sub POE::Kernel::CATCH_EXCEPTIONS () { 0 } \& use POE; .Ve .SS "Signal Watcher Methods" .IX Subsection "Signal Watcher Methods" And finally the methods themselves. .PP \fIsig \s-1SIGNAL_NAME\s0 [, \s-1EVENT_NAME\s0 [, \s-1LIST\s0] ]\fR .IX Subsection "sig SIGNAL_NAME [, EVENT_NAME [, LIST] ]" .PP \&\fBsig()\fR registers or unregisters an \s-1EVENT_NAME\s0 event for a particular \&\s-1SIGNAL_NAME,\s0 with an optional \s-1LIST\s0 of parameters that will be passed to the signal's handler\-\-\-after any data that comes wit the signal. .PP If \s-1EVENT_NAME\s0 is defined, the signal handler is registered. Otherwise it's unregistered. .PP Each session can register only one handler per \s-1SIGNAL_NAME.\s0 Subsequent registrations will replace previous ones. Multiple sessions may however watch the same signal. .PP SIGNAL_NAMEs are generally the same as members of \f(CW%SIG\fR, with two exceptions. First, \f(CW\*(C`CLD\*(C'\fR is an alias for \f(CW\*(C`CHLD\*(C'\fR (although see \&\*(L"sig_child\*(R"). And second, it's possible to send and handle signals created by the application and have no basis in the operating system. .PP .Vb 5 \& sub handle_start { \& $_[KERNEL]\->sig( INT => "event_ui_shutdown" ); \& $_[KERNEL]\->sig( bat => "holy_searchlight_batman" ); \& $_[KERNEL]\->sig( signal => "main_screen_turn_on" ); \& } .Ve .PP The operating system may never be able to generate the last two signals, but a \s-1POE\s0 session can by using POE::Kernel's \&\*(L"signal\*(R"() method. .PP Later on the session may decide not to handle the signals: .PP .Vb 5 \& sub handle_ui_shutdown { \& $_[KERNEL]\->sig( "INT" ); \& $_[KERNEL]\->sig( "bat" ); \& $_[KERNEL]\->sig( "signal" ); \& } .Ve .PP More than one session may register interest in the same signal, and a session may clear its own signal watchers without affecting those in other sessions. .PP \&\fBsig()\fR does not return a meaningful value. .PP \fIsig_child \s-1PROCESS_ID\s0 [, \s-1EVENT_NAME\s0 [, \s-1LIST\s0] ]\fR .IX Subsection "sig_child PROCESS_ID [, EVENT_NAME [, LIST] ]" .PP \&\fBsig_child()\fR is a convenient way to deliver an \s-1EVENT_NAME\s0 event when a particular \s-1PROCESS_ID\s0 has exited. An optional \s-1LIST\s0 of parameters will be passed to the signal handler after the \fBwaitpid()\fR information. .PP The watcher can be cleared at any time by calling \fBsig_child()\fR with just the \s-1PROCESS_ID.\s0 .PP A session may register as many \fBsig_child()\fR handlers as necessary, but a session may only have one per \s-1PROCESS_ID.\s0 .PP \&\fBsig_child()\fR watchers are one-shot. They automatically unregister themselves once the \s-1EVENT_NAME\s0 has been delivered. There's no point in continuing to watch for a signal that will never come again. Other signal handlers persist until they are cleared. .PP \&\fBsig_child()\fR watchers keep a session alive for as long as they are active. This is unique among \s-1POE\s0's signal watchers. .PP Programs that wish to reliably reap child processes should be sure to call \fBsig_child()\fR before returning from the event handler that forked the process. Otherwise POE::Kernel may have an opportunity to call \&\fBwaitpid()\fR before an appropriate event watcher has been registered. .PP Programs that reap processes with \fBwaitpid()\fR must clear \s-1POE\s0's watchers for the same process IDs, otherwise \s-1POE\s0 will wait indefinitely for processes that never send signals. .PP \&\fBsig_child()\fR does not return a meaningful value. .PP .Vb 4 \& sub forked_parent { \& my( $heap, $pid, $details ) = @_[ HEAP, ARG0, ARG1 ]; \& $poe_kernel\->sig_child( $pid, \*(Aqsig_child\*(Aq, $details ); \& } \& \& sub sig_child { \& my( $heap, $sig, $pid, $exit_val, $details ) = @_[ HEAP, ARG0..ARG3 ]; \& my $details = delete $heap\->{ $pid }; \& warn "$$: Child $pid exited" \& # .... also, $details has been passed from forked_parent() \& # through sig_child() \& } .Ve .PP \fIsig_handled\fR .IX Subsection "sig_handled" .PP \&\fBsig_handled()\fR informs POE::Kernel that the currently dispatched signal has been handled by the currently active session. If the signal is terminal, the \&\fBsig_handled()\fR call prevents POE::Kernel from stopping the sessions that received the signal. .PP A single signal may be dispatched to several sessions. Only one needs to call \fBsig_handled()\fR to prevent the entire group from being stopped. If none of them call it, however, then they are all stopped together. .PP \&\fBsig_handled()\fR does not return a meaningful value. .PP .Vb 3 \& sub _start { \& $_[KERNEL]\->sig( INT => \*(Aqsig_INT\*(Aq ); \& } \& \& sub sig_INT { \& warn "$$ SIGINT"; \& $_[KERNEL]\->sig_handled(); \& } .Ve .PP \fIsignal \s-1SESSION, SIGNAL_NAME\s0 [, \s-1ARGS_LIST\s0]\fR .IX Subsection "signal SESSION, SIGNAL_NAME [, ARGS_LIST]" .PP \&\fBsignal()\fR posts a \s-1SIGNAL_NAME\s0 signal to a specific \s-1SESSION\s0 with an optional \s-1ARGS_LIST\s0 that will be passed to every interested handler. As mentioned elsewhere, the signal may be delivered to \s-1SESSION\s0's children, grandchildren, and so on. And if \s-1SESSION\s0 is the POE::Kernel itself, then all interested sessions will receive the signal. .PP It is possible to send a signal in \s-1POE\s0 that doesn't exist in the operating system. \fBsignal()\fR places the signal directly into \s-1POE\s0's event queue as if they came from the operating system, but they are not limited to signals recognized by \fBkill()\fR. \s-1POE\s0 uses a few of these fictitious signals for its own global notifications. .PP For example: .PP .Vb 4 \& sub some_event_handler { \& # Turn on all main screens. \& $_[KERNEL]\->signal( $_[KERNEL], "signal" ); \& } .Ve .PP \&\fBsignal()\fR returns true on success. On failure, it returns false after setting $! to explain the nature of the failure: .ie n .IP "\s-1ESRCH\s0 (""No such process"")" 4 .el .IP "\s-1ESRCH\s0 (``No such process'')" 4 .IX Item "ESRCH (No such process)" The \s-1SESSION\s0 does not exist. .PP Because all sessions are a child of POE::Kernel, sending a signal to the kernel will propagate the signal to all sessions. This is a cheap form of \fImulticast\fR. .PP .Vb 1 \& $_[KERNEL]\->signal( $_[KERNEL], \*(Aqshutdown\*(Aq ); .Ve .PP \fIsignal_ui_destroy \s-1WIDGET_OBJECT\s0\fR .IX Subsection "signal_ui_destroy WIDGET_OBJECT" .PP \&\fBsignal_ui_destroy()\fR associates the destruction of a particular \&\s-1WIDGET_OBJECT\s0 with the complete destruction of the program's user interface. When the \s-1WIDGET_OBJECT\s0 destructs, POE::Kernel issues the non-maskable \s-1UIDESTROY\s0 signal, which quickly triggers mass destruction of all active sessions. POE::Kernel\->\fBrun()\fR returns shortly thereafter. .PP .Vb 5 \& sub setup_ui { \& $_[HEAP]{main_widget} = Gtk\->new("toplevel"); \& # ... populate the main widget here ... \& $_[KERNEL]\->signal_ui_destroy( $_[HEAP]{main_widget} ); \& } .Ve .PP Detecting widget destruction is specific to each toolkit. .SS "Event Handler Management" .IX Subsection "Event Handler Management" Event handler management methods let sessions hot swap their event handlers at run time. For example, the POE::Wheel objects use \fBstate()\fR to dynamically mix their own event handlers into the sessions that create them. .PP These methods only affect the current session; it would be rude to change another session's handlers. .PP There is only one method in this group. Since it may be called in several different ways, it may be easier to understand if each is documented separately. .PP \fIstate \s-1EVENT_NAME\s0 [, \s-1CODE_REFERNCE\s0]\fR .IX Subsection "state EVENT_NAME [, CODE_REFERNCE]" .PP \&\fBstate()\fR sets or removes a handler for \s-1EVENT_NAME\s0 in the current session. The function referred to by \s-1CODE_REFERENCE\s0 will be called whenever \s-1EVENT_NAME\s0 events are dispatched to the current session. If \&\s-1CODE_REFERENCE\s0 is omitted, the handler for \s-1EVENT_NAME\s0 will be removed. .PP A session may only have one handler for a given \s-1EVENT_NAME.\s0 Subsequent attempts to set an \s-1EVENT_NAME\s0 handler will replace earlier handlers with the same name. .PP .Vb 7 \& # Stop paying attention to input. Say goodbye, and \& # trigger a socket close when the message is sent. \& sub send_final_response { \& $_[HEAP]{wheel}\->put("KTHXBYE"); \& $_[KERNEL]\->state( \*(Aqon_client_input\*(Aq ); \& $_[KERNEL]\->state( on_flush => \e&close_connection ); \& } .Ve .PP \fIstate \s-1EVENT_NAME\s0 [, \s-1OBJECT_REFERENCE\s0 [, \s-1OBJECT_METHOD_NAME\s0] ]\fR .IX Subsection "state EVENT_NAME [, OBJECT_REFERENCE [, OBJECT_METHOD_NAME] ]" .PP Set or remove a handler for \s-1EVENT_NAME\s0 in the current session. If an \&\s-1OBJECT_REFERENCE\s0 is given, that object will handle the event. An optional \s-1OBJECT_METHOD_NAME\s0 may be provided. If the method name is not given, \s-1POE\s0 will look for a method matching the \s-1EVENT_NAME\s0 instead. If the \s-1OBJECT_REFERENCE\s0 is omitted, the handler for \s-1EVENT_NAME\s0 will be removed. .PP A session may only have one handler for a given \s-1EVENT_NAME.\s0 Subsequent attempts to set an \s-1EVENT_NAME\s0 handler will replace earlier handlers with the same name. .PP .Vb 2 \& $_[KERNEL]\->state( \*(Aqsome_event\*(Aq, $self ); \& $_[KERNEL]\->state( \*(Aqother_event\*(Aq, $self, \*(Aqother_method\*(Aq ); .Ve .PP \fIstate \s-1EVENT_NAME\s0 [, \s-1CLASS_NAME\s0 [, \s-1CLASS_METHOD_NAME\s0] ]\fR .IX Subsection "state EVENT_NAME [, CLASS_NAME [, CLASS_METHOD_NAME] ]" .PP This form of \fBstate()\fR call is virtually identical to that of the object form. .PP Set or remove a handler for \s-1EVENT_NAME\s0 in the current session. If an \&\s-1CLASS_NAME\s0 is given, that class will handle the event. An optional \&\s-1CLASS_METHOD_NAME\s0 may be provided. If the method name is not given, \&\s-1POE\s0 will look for a method matching the \s-1EVENT_NAME\s0 instead. If the \&\s-1CLASS_NAME\s0 is omitted, the handler for \s-1EVENT_NAME\s0 will be removed. .PP A session may only have one handler for a given \s-1EVENT_NAME.\s0 Subsequent attempts to set an \s-1EVENT_NAME\s0 handler will replace earlier handlers with the same name. .PP .Vb 2 \& $_[KERNEL]\->state( \*(Aqsome_event\*(Aq, _\|_PACKAGE_\|_ ); \& $_[KERNEL]\->state( \*(Aqother_event\*(Aq, _\|_PACKAGE_\|_, \*(Aqother_method\*(Aq ); .Ve .SS "Public Reference Counters" .IX Subsection "Public Reference Counters" The methods in this section manipulate reference counters on the current session or another session. .PP Each session has a namespace for user-manipulated reference counters. These namespaces are associated with the target \s-1SESSION_ID\s0 for the reference counter methods, not the caller. Nothing currently prevents one session from decrementing a reference counter that was incremented by another, but this behavior is not guaranteed to remain. For now, it's up to the users of these methods to choose obscure counter names to avoid conflicts. .PP Reference counting is a big part of \s-1POE\s0's magic. Various objects (mainly event watchers and components) hold references to the sessions that own them. \*(L"Session Lifespans\*(R" explains the concept in more detail. .PP The ability to keep a session alive is sometimes useful in an application or library. For example, a component may hold a public reference to another session while it processes a request from that session. In doing so, the component guarantees that the requester is still around when a response is eventually ready. Keeping a reference to the session's object is not enough. POE::Kernel has its own internal reference counting mechanism. .PP \fIrefcount_increment \s-1SESSION_ID, COUNTER_NAME\s0\fR .IX Subsection "refcount_increment SESSION_ID, COUNTER_NAME" .PP \&\fBrefcount_increment()\fR increases the value of the \s-1COUNTER_NAME\s0 reference counter for the session identified by a \s-1SESSION_ID.\s0 To discourage the use of session references, the \fBrefcount_increment()\fR target session must be specified by its session \s-1ID.\s0 .PP The target session will not stop until the value of any and all of its \&\s-1COUNTER_NAME\s0 reference counters are zero. (Actually, it may stop in some cases, such as failing to handle a terminal signal.) .PP Negative reference counters are legal. They still must be incremented back to zero before a session is eligible for stopping. .PP .Vb 5 \& sub handle_request { \& # Among other things, hold a reference count on the sender. \& $_[KERNEL]\->refcount_increment( $_[SENDER]\->ID, "pending request"); \& $_[HEAP]{requesters}{$request_id} = $_[SENDER]\->ID; \& } .Ve .PP For this to work, the session needs a way to remember the \&\f(CW$_\fR[\s-1SENDER\s0]\->\s-1ID\s0 for a given request. Customarily the session generates a request \s-1ID\s0 and uses that to track the request until it is fulfilled. .PP \&\fBrefcount_increment()\fR returns the resulting reference count (which may be zero) on success. On failure, it returns undef and sets $! to be the reason for the error. .PP \&\s-1ESRCH:\s0 The \s-1SESSION_ID\s0 does not refer to a currently active session. .PP \fIrefcount_decrement \s-1SESSION_ID, COUNTER_NAME\s0\fR .IX Subsection "refcount_decrement SESSION_ID, COUNTER_NAME" .PP \&\fBrefcount_decrement()\fR reduces the value of the \s-1COUNTER_NAME\s0 reference counter for the session identified by a \s-1SESSION_ID.\s0 It is the counterpoint for \fBrefcount_increment()\fR. Please see \&\fBrefcount_increment()\fR for more context. .PP .Vb 6 \& sub finally_send_response { \& # Among other things, release the reference count for the \& # requester. \& my $requester_id = delete $_[HEAP]{requesters}{$request_id}; \& $_[KERNEL]\->refcount_decrement( $requester_id, "pending request"); \& } .Ve .PP The requester's \f(CW$_\fR[\s-1SENDER\s0]\->\s-1ID\s0 is remembered and removed from the heap (lest there be memory leaks). It's used to decrement the reference counter that was incremented at the start of the request. .PP \&\fBrefcount_decrement()\fR returns the resulting reference count (which may be zero) on success. On failure, it returns undef, and $! will be set to the reason for the failure: .PP \&\s-1ESRCH:\s0 The \s-1SESSION_ID\s0 does not refer to a currently active session. .PP It is not possible to discover currently active public references. See POE::API::Peek. .SS "Kernel State Accessors" .IX Subsection "Kernel State Accessors" POE::Kernel provides a few accessors into its massive brain so that library developers may have convenient access to necessary data without relying on their callers to provide it. .PP These accessors expose ways to break session encapsulation. Please use them sparingly and carefully. .PP \fIget_active_session\fR .IX Subsection "get_active_session" .PP \&\fBget_active_session()\fR returns a reference to the session that is currently running, or a reference to the program's POE::Kernel instance if no session is running at that moment. The value is equivalent to POE::Session's \f(CW$_[SESSION]\fR. .PP This method was added for libraries that need \f(CW$_[SESSION]\fR but don't want to include it as a parameter in their APIs. .PP .Vb 5 \& sub some_housekeeping { \& my( $self ) = @_; \& my $session = $poe_kernel\->get_active_session; \& # do some housekeeping on $session \& } .Ve .PP \fIget_active_event\fR .IX Subsection "get_active_event" .PP \&\fBget_active_event()\fR returns the name of the event currently being dispatched. It returns an empty string when called outside event dispatch. The value is equivalent to POE::Session's \&\f(CW$_[STATE]\fR. .PP .Vb 5 \& sub waypoint { \& my( $message ) = @_; \& my $event = $poe_kernel\->get_active_event; \& print STDERR "$$:$event:$mesage\en"; \& } .Ve .PP \fIget_event_count\fR .IX Subsection "get_event_count" .PP \&\fBget_event_count()\fR returns the number of events pending in \s-1POE\s0's event queue. It is exposed for POE::Loop class authors. It may be deprecated in the future. .PP \fIget_next_event_time\fR .IX Subsection "get_next_event_time" .PP \&\fBget_next_event_time()\fR returns the time the next event is due, in a form compatible with the \s-1UNIX\s0 \fBtime()\fR function. It is exposed for POE::Loop class authors. It may be deprecated in the future. .PP \fIpoe_kernel_loop\fR .IX Subsection "poe_kernel_loop" .PP \&\fBpoe_kernel_loop()\fR returns the name of the POE::Loop class that is used to detect and dispatch events. .SS "Session Helper Methods" .IX Subsection "Session Helper Methods" The methods in this group expose features for POE::Session class authors. .PP \fIsession_alloc \s-1SESSION_OBJECT\s0 [, \s-1START_ARGS\s0]\fR .IX Subsection "session_alloc SESSION_OBJECT [, START_ARGS]" .PP \&\fBsession_alloc()\fR allocates a session context within POE::Kernel for a newly created \s-1SESSION_OBJECT.\s0 A list of optional \s-1START_ARGS\s0 will be passed to the session as part of the \*(L"_start\*(R" event. .PP The \s-1SESSION_OBJECT\s0 is expected to follow a subset of POE::Session's interface. .PP There is no \fBsession_free()\fR. POE::Kernel determines when the session should stop and performs the necessary cleanup after dispatching _stop to the session. .SS "Miscellaneous Methods" .IX Subsection "Miscellaneous Methods" We don't know where to classify the methods in this section. .PP \fInew\fR .IX Subsection "new" .PP It is not necessary to call POE::Kernel's \fBnew()\fR method. Doing so will return the program's singleton POE::Kernel object, however. .SH "PUBLIC EXPORTED VARIABLES" .IX Header "PUBLIC EXPORTED VARIABLES" POE::Kernel exports two variables for your coding enjoyment: \&\f(CW$poe_kernel\fR and \f(CW$poe_main_window\fR. POE::Kernel is implicitly used by \s-1POE\s0 itself, so using \s-1POE\s0 gets you POE::Kernel (and its exports) for free. .PP In more detail: .ie n .SS "$poe_kernel" .el .SS "\f(CW$poe_kernel\fP" .IX Subsection "$poe_kernel" \&\f(CW$poe_kernel\fR contains a reference to the process' POE::Kernel singleton instance. It's mainly used for accessing POE::Kernel methods from places where \f(CW$_[KERNEL]\fR is not available. It's most commonly used in helper libraries. .ie n .SS "$poe_main_window" .el .SS "\f(CW$poe_main_window\fP" .IX Subsection "$poe_main_window" \&\f(CW$poe_main_window\fR is used by graphical toolkits that require at least one widget to be created before their event loops are usable. This is currently only Tk. .PP POE::Loop::Tk creates a main window to satisfy Tk's event loop. The window is given to the application since \s-1POE\s0 has no other use for it. .PP \&\f(CW$poe_main_window\fR is undefined in toolkits that don't require a widget to dispatch events. .PP On a related note, \s-1POE\s0 will shut down if the widget in \&\f(CW$poe_main_window\fR is destroyed. This can be changed with POE::Kernel's \*(L"signal_ui_destroy\*(R" method. .SH "DEBUGGING POE AND PROGRAMS USING IT" .IX Header "DEBUGGING POE AND PROGRAMS USING IT" \&\s-1POE\s0 includes quite a lot of debugging code, in the form of both fatal assertions and run-time traces. They may be enabled at compile time, but there is no way to toggle them at run-time. This was done to avoid run-time penalties in programs where debugging is not necessary. That is, in most production cases. .PP Traces are verbose reminders of what's going on within \s-1POE.\s0 Each is prefixed with a four-character field describing the \s-1POE\s0 subsystem that generated it. .PP Assertions (asserts) are quiet but deadly, both in performance (they cause a significant run-time performance hit) and because they cause fatal errors when triggered. .PP The assertions and traces are useful for developing programs with \s-1POE,\s0 but they were originally added to debug \s-1POE\s0 itself. .PP Each assertion and tracing group is enabled by setting a constant in the POE::Kernel namespace to a true value. .PP .Vb 5 \& BEGIN { \& package POE::Kernel; \& use constant ASSERT_DEFAULT => 1; \& } \& use POE; .Ve .PP Or the old-fashioned (and more concise) \*(L"constant subroutine\*(R" method. This doesn't need the \f(CW\*(C`BEGIN{}\*(C'\fR block since subroutine definitions are done at compile time. .PP .Vb 2 \& sub POE::Kernel::ASSERT_DEFAULT () { 1 } \& use POE; .Ve .PP The switches must be defined as constants before POE::Kernel is first loaded. Otherwise Perl's compiler will not see the constants when first compiling POE::Kernel, and the features will not be properly enabled. .PP Assertions and traces may also be enabled by setting shell environment variables. The environment variables are named after the POE::Kernel constants with a \*(L"\s-1POE_\*(R"\s0 prefix. .PP .Vb 1 \& POE_ASSERT_DEFAULT=1 POE_TRACE_DEFAULT=1 ./my_poe_program .Ve .PP In alphabetical order: .SS "\s-1ASSERT_DATA\s0" .IX Subsection "ASSERT_DATA" \&\s-1ASSERT_DATA\s0 enables run-time data integrity checks within POE::Kernel and the classes that mix into it. POE::Kernel tracks a lot of cross-referenced data, and this group of assertions ensures that it's consistent. .PP Prefix:
.PP Environment variable: \s-1POE_ASSERT_DATA\s0 .SS "\s-1ASSERT_DEFAULT\s0" .IX Subsection "ASSERT_DEFAULT" \&\s-1ASSERT_DEFAULT\s0 specifies the default value for assertions that are not explicitly enabled or disabled. This is a quick and reliable way to make sure all assertions are on. .PP No assertion uses \s-1ASSERT_DEFAULT\s0 directly, and this assertion flag has no corresponding output prefix. .PP Turn on all assertions except \s-1ASSERT_EVENTS:\s0 .PP .Vb 3 \& sub POE::Kernel::ASSERT_DEFAULT () { 1 } \& sub POE::Kernel::ASSERT_EVENTS () { 0 } \& use POE::Kernel; .Ve .PP Prefix: (none) .PP Environment variable: \s-1POE_ASSERT_DEFAULT\s0 .SS "\s-1ASSERT_EVENTS\s0" .IX Subsection "ASSERT_EVENTS" \&\s-1ASSERT_EVENTS\s0 mainly checks for attempts to dispatch events to sessions that don't exist. This assertion can assist in the debugging of strange, silent cases where event handlers are not called. .PP Prefix: .PP Environment variable: \s-1POE_ASSERT_EVENTS\s0 .SS "\s-1ASSERT_FILES\s0" .IX Subsection "ASSERT_FILES" \&\s-1ASSERT_FILES\s0 enables some run-time checks in \s-1POE\s0's filehandle watchers and the code that manages them. .PP Prefix: .PP Environment variable: \s-1POE_ASSERT_FILES\s0 .SS "\s-1ASSERT_RETVALS\s0" .IX Subsection "ASSERT_RETVALS" \&\s-1ASSERT_RETVALS\s0 upgrades failure codes from POE::Kernel's methods from advisory return values to fatal errors. Most programmers don't check the values these methods return, so \s-1ASSERT_RETVALS\s0 is a quick way to validate one's assumption that all is correct. .PP Prefix: .PP Environment variable: \s-1POE_ASSERT_RETVALS\s0 .SS "\s-1ASSERT_USAGE\s0" .IX Subsection "ASSERT_USAGE" \&\s-1ASSERT_USAGE\s0 is the counterpoint to \s-1ASSERT_RETVALS.\s0 It enables run-time checks that the parameters to POE::Kernel's methods are correct. It's a quick (but not foolproof) way to verify a program's use of \s-1POE.\s0 .PP Prefix: .PP Environment variable: \s-1POE_ASSERT_USAGE\s0 .SS "\s-1TRACE_DEFAULT\s0" .IX Subsection "TRACE_DEFAULT" \&\s-1TRACE_DEFAULT\s0 specifies the default value for traces that are not explicitly enabled or disabled. This is a quick and reliable way to ensure your program generates copious output on the file named in \&\s-1TRACE_FILENAME\s0 or \s-1STDERR\s0 by default. .PP To enable all traces except a few noisier ones: .PP .Vb 3 \& sub POE::Kernel::TRACE_DEFAULT () { 1 } \& sub POE::Kernel::TRACE_EVENTS () { 0 } \& use POE::Kernel; .Ve .PP Prefix: (none) .PP Environment variable: \s-1POE_TRACE_DEFAULT\s0 .SS "\s-1TRACE_DESTROY\s0" .IX Subsection "TRACE_DESTROY" \&\s-1TRACE_DESTROY\s0 causes every POE::Session object to dump the contents of its \f(CW$_[HEAP]\fR when Perl destroys it. This trace was added to help developers find memory leaks in their programs. .PP Prefix: A line that reads \*(L"\-\-\-\-\- Session \f(CW$self\fR Leak Check \-\-\-\-\-\*(R". .PP Environment variable: \s-1POE_TRACE_DESTROY\s0 .SS "\s-1TRACE_EVENTS\s0" .IX Subsection "TRACE_EVENTS" \&\s-1TRACE_EVENTS\s0 enables messages pertaining to \s-1POE\s0's event queue's activities: when events are enqueued, dispatched or discarded, and more. It's great for determining where events go and when. Understandably this is one of \s-1POE\s0's more verbose traces. .PP Prefix: .PP Environment variable: \s-1POE_TRACE_EVENTS\s0 .SS "\s-1TRACE_FILENAME\s0" .IX Subsection "TRACE_FILENAME" \&\s-1TRACE_FILENAME\s0 specifies the name of a file where \s-1POE\s0's tracing and assertion messages should go. It's useful if you want the messages but have other plans for \s-1STDERR,\s0 which is where the messages go by default. .PP \&\s-1POE\s0's tests use this so the trace and assertion code can be instrumented during testing without spewing all over the terminal. .PP Prefix: (none) .PP Environment variable: \s-1POE_TRACE_FILENAME\s0 .SS "\s-1TRACE_FILES\s0" .IX Subsection "TRACE_FILES" \&\s-1TRACE_FILES\s0 enables or disables traces in \s-1POE\s0's filehandle watchers and the POE::Loop class that implements the lowest-level filehandle multiplexing. This may be useful when tracking down strange behavior related to filehandles. .PP Prefix: .PP Environment variable: \s-1POE_TRACE_FILES\s0 .SS "\s-1TRACE_REFCNT\s0" .IX Subsection "TRACE_REFCNT" \&\s-1TRACE_REFCNT\s0 governs whether POE::Kernel will trace sessions' reference counts. As discussed in \*(L"Session Lifespans\*(R", \s-1POE\s0 does a lot of reference counting, and the current state of a session's reference counts determines whether the session lives or dies. It's common for developers to wonder why a session stops too early or remains active too long. \s-1TRACE_REFCNT\s0 can help explain why. .PP Prefix: .PP Environment variable: \s-1POE_TRACE_REFCNT\s0 .SS "\s-1TRACE_RETVALS\s0" .IX Subsection "TRACE_RETVALS" \&\s-1TRACE_RETVALS\s0 can enable carping whenever a POE::Kernel method is about to fail. It's a non-fatal but noisier form of \&\s-1ASSERT_RETVALS.\s0 .PP Prefix: .PP Environment variable: \s-1POE_TRACE_RETVALS\s0 .SS "\s-1TRACE_SESSIONS\s0" .IX Subsection "TRACE_SESSIONS" \&\s-1TRACE_SESSIONS\s0 enables trace messages that pertain to session management. Notice will be given when sessions are created or destroyed, and when the parent or child status of a session changes. .PP Prefix: .PP Environment variable: \s-1POE_TRACE_SESSIONS\s0 .SS "\s-1TRACE_SIGNALS\s0" .IX Subsection "TRACE_SIGNALS" \&\s-1TRACE_SIGNALS\s0 turns on (or off) traces in \s-1POE\s0's signal handling subsystem. Signal dispatch is one of \s-1POE\s0's more complex parts, and the trace messages may help application developers understand signal propagation and timing. .PP Prefix: .PP Environment variable: \s-1POE_TRACE_SIGNALS\s0 .SS "\s-1USE_SIGCHLD\s0" .IX Subsection "USE_SIGCHLD" Whether to use \f(CW$SIG{CHLD}\fR or to poll at an interval. .PP This flag is enabled by default on Perl >= 5.8.1 as it has support for \*(L"safe signals\*(R". Please see perlipc for the gory details. .PP You might want to disable this if you are running a version of Perl that is known to have bad signal handling, or if anything hijacks \f(CW$SIG{CHLD}\fR. One module that is known to do this is Apache. .PP Enabling this flag will cause child reaping to happen almost immediately, as opposed to once per \*(L"\s-1CHILD_POLLING_INTERVAL\*(R"\s0. .SS "\s-1CHILD_POLLING_INTERVAL\s0" .IX Subsection "CHILD_POLLING_INTERVAL" The interval at which \f(CW\*(C`wait\*(C'\fR is called to determine if child processes need to be reaped and the \f(CW\*(C`CHLD\*(C'\fR signal emulated. .PP Defaults to 1 second. .SS "\s-1USE_SIGNAL_PIPE\s0" .IX Subsection "USE_SIGNAL_PIPE" The only safe way to handle signals is to implement a shared-nothing model. \s-1POE\s0 builds a \fIsignal pipe\fR that communicates between the signal handlers and the \s-1POE\s0 kernel loop in a safe and atomic manner. The signal pipe is implemented with POE::Pipe::OneWay, using a \&\f(CW\*(C`pipe\*(C'\fR conduit on Unix. Unfortunately, the signal pipe is not compatible with Windows and is not used on that platform. .PP If you wish to revert to the previous unsafe signal behaviour, you must set \f(CW\*(C`USE_SIGNAL_PIPE\*(C'\fR to 0, or the environment variable \&\f(CW\*(C`POE_USE_SIGNAL_PIPE\*(C'\fR. .SS "\s-1CATCH_EXCEPTIONS\s0" .IX Subsection "CATCH_EXCEPTIONS" Whether or not \s-1POE\s0 should run event handler code in an eval { } and deliver the \f(CW\*(C`DIE\*(C'\fR signal on errors. .PP See \*(L"Exception Handling\*(R". .SH "ENVIRONMENT VARIABLES FOR TESTING" .IX Header "ENVIRONMENT VARIABLES FOR TESTING" \&\s-1POE\s0's tests are lovely, dark and deep. These environment variables allow testers to take roads less traveled. .SS "\s-1POE_DANTIC\s0" .IX Subsection "POE_DANTIC" Windows and Perls built for it tend to be poor at doing UNIXy things, although they do try. \s-1POE\s0 being very UNIXy itself must skip a lot of Windows tests. The \s-1POE_DANTIC\s0 environment variable will, when true, enable all these tests. It's intended to be used from time to time to see whether Windows has improved in some area. .SH "SEE ALSO" .IX Header "SEE ALSO" The \s-1SEE ALSO\s0 section in \s-1POE\s0 contains a table of contents covering the entire \s-1POE\s0 distribution. .SH "BUGS" .IX Header "BUGS" .IP "\(bu" 4 There is no mechanism in place to prevent external reference count names from clashing. .IP "\(bu" 4 There is no mechanism to catch exceptions generated in another session. .SH "AUTHORS & COPYRIGHTS" .IX Header "AUTHORS & COPYRIGHTS" Please see \s-1POE\s0 for more information about authors and contributors.