POE::Kernel - POE Event Queue and Resource Manager |
POE::Kernel - POE Event Queue and Resource Manager
#!/usr/bin/perl -w use strict; use POE; # Includes POE::Kernel and POE::Session print $poe_kernel->ID(); # This process' unique ID. new POE::Session( ... ); # Bootstrap sessions are here. $poe_kernel->run(); # Run the kernel. exit; # Exit when the kernel's done.
# Session management methods: $kernel->session_create( ... );
# Event management methods: $kernel->post( $session, $state, @args ); $kernel->yield( $state, @args ); $kernel->call( $session, $state, @args );
# Alarms and timers: $kernel->alarm( $state, $time, @args ); $kernel->delay( $state, $seconds, @args );
# Aliases: $status = $kernel->alias_set( $alias ); $status = $kernel->alias_remove( $alias ); $session_reference = $kernel->alias_resolve( $alias );
# Selects: $kernel->select( $file_handle, $read_state_name, # or undef to remove it $write_state_name, # or undef to remove it $expedite_state_same, # or undef to remove it ); $kernel->select_read( $file_handle, $read_state_name ); $kernel->select_write( $file_handle, $write_state_name ); $kernel->select_expedite( $file_handle, $expedite_state_name );
# Signals: $kernel->sig( $signal_name, $state_name ); # Registers a handler. $kernel->signal( $session, $signal_name ); # Posts a signal.
# Processes. $kernel->fork(); # "Safe" fork that polls for SIGCHLD.
# States: $kernel->state( $state_name, $code_reference ); # Inline state $kernel->state( $method_name, $object_reference ); # Object state $kernel->state( $function_name, $package_name ); # Package state $kernel->state( $state_name, # Object or package $object_or_package_reference, # state, mapped to $object_or_package_method, # different method. );
# IDs: $kernel->ID(); # Return the Kernel's unique ID. $kernel->ID_id_to_session($id); # Return undef, or the ID's session. $kernel->ID_session_to_id($session); # Return undef, or the session's ID.
POE::Kernel contains POE's event loop, select logic and resource management methods. There can only be one POE::Kernel per process, and it's created automatically the first time POE::Kernel is used. This simplifies signal delivery in the present and threads support in the future.
POE::Kernel exports $poe_kernel, a reference to the program's single
kernel instance. This mainly is used in the main package, so that
$poe_kernel->run()
may be called cleanly.
Sessions' states should endeavor to use $_[KERNEL], since $poe_kernel may not be available, or it may be different than the kernel actually invoking the object.
POE::Kernel contains methods to manage the kernel itself, sessions, and resources such as files, signals and alarms.
Many of the public Kernel methods generate events. Please see the ``PREDEFINED EVENTS AND PARAMETERS'' section in POE::Session's documentation.
POE::Kernel::run() starts the kernel's event loop. It will not return until all its sessions have stopped. There are two corollaries to this rule: It will return immediately if there are no sessions; and if sessions never exit, neither will run().
POE::Kernel::session_create(...) creates a new session in the kernel. It is an alias for POE::Session::new(...), and it accepts the same parameters. Please see POE::Session::new(...) for more information.
As of version 0.07, POE::Session is a proper object with public methods and everything. Therefore session_create is depreciated starting with version 0.07.
Events tell sessions which state to invoke next. States are defined when sessions are created. States may also be added, removed or changed at runtime by POE::Kernel::state(), which acts on the current session.
There are a few ways to send events to sessions. Events can be
posted, in which case the kernel queues them and dispatches them in
FIFO order. States can also be called immediately, bypassing the
queue. Immediate calls can be useful for ``critical sections''; for
example, POE's I/O abstractions use call()
to minimize event latency.
To learn more about events and the information they convey, please see ``PREDEFINED EVENTS AND PARAMETERS'' in the POE::Session documentation.
POE::Kernel::post places an event in the kernel's queue. The kernel dispatches queued events in FIFO order. When posted events are dispatched, their corresponding states are invoked in a scalar context, and their return values are discarded. Signal handlers work differently, but they're not invoked as a result of post().
If a state's return value is important, there are at least two ways to get it. First, have the $destination post a return vent to its $_[SENDER]; second, use POE::Kernel::call() instead.
POE::Kernel::post returns undef on failure, or an unspecified defined value on success. $! is set to the reason why the post failed.
POE::Kernel::yield is an alias for posting an event to the current
session. It does not immediately swap call stacks like yield()
in
real thread libraries might. If there's a way to do this in perl, I'd
sure like to know.
POE::Kernel::call immediately dispatches an event to a session.
States invoked this way are evaluated in a scalar context, and call()
returns their return values.
call()
can exercise bugs in perl and/or the C library (we're not
really sure which just yet). This only seems to occur when one state
(state1) is destroyed from another state (state0) as a result of
state0 being called from state1.
Until that bug is pinned down and fixed, if your program dumps core with a SIGSEGV, try changing your call()s to post()s.
call()
returns undef on failure. It may also return undef on success,
if the called state returns success. What a mess. call()
also sets
$! to 0 on success, regardless of what it's set to in the called
state.
Alarms are just events that are scheduled to be dispatched at some
later time. POE's queue is a priority queue keyed on time, so these
events go to the appropriate place in the queue. Posted events are
really enqueued for ``now'' (defined as whatever time()
returns).
If Time::HiRes is available, POE will use it to achieve better resolution on enqueued events.
The alarm()
method enqueues an event with a future dispatch time,
specified in seconds since whatever epoch time()
uses (usually the
UNIX epoch). If $time is in the past, it will be clipped to time(),
making the alarm()
call synonymous to post()
but with some extra
overhead.
Alarms are keyed by state name. That is, there can be only one pending alarm for any given state. This is a design bug, and there are plans to fix it.
It is possible to remove an alarm that hasn't yet been dispatched:
$kernel->alarm( $state ); # Removes the alarm for $state
Subsequent alarms set for the same name will overwrite previous ones. This is useful for timeout timers that must be continually refreshed.
The alarm()
method can be misused to remove events from the kernel's
queue. This happens because alarms are merely events scheduled for a
future time. This behavior is considered to be a bug, and there are
plans to fix it.
The delay()
method is an alias for:
$kernel->alarm( $state, time() + $seconds, @args );
However, because time()
is called within the POE::Kernel package, it
uses Time::HiRes if it's available. This saves programs from having
to figure out if Time::HiRes is available themselves.
All the details for POE::Kernel::alarm() apply to delay()
as well.
For example, delays may be removed by omitting the $seconds and @args
parameters:
$kernel->delay( $state ); # Removes the delay for $state
And delay()
can be misused to remove events from the kernel's queue.
Please see POE::Kernel::alarm() for more information.
Aliases allow sessions to be referenced by name instead of by session reference. They also allow sessions to remain active without having selects or events. This provides support for ``daemon'' sessions that act as resources but don't necessarily have resources themselves.
Aliases must be unique. Sessions may have more than one alias.
The alias_set()
method sets an alias for the current session.
It returns 1 on success. On failure, it returns 0 and sets $! to one of:
EEXIST - The alias already exists for another session.
The alias_remove()
method removes an alias for the current session.
It returns 1 on success. On failure, it returns 0 and sets $! to one of:
ESRCH - The alias does not exist. EPERM - The alias belongs to another session.
The alias_resolve()
method returns a session reference corresponding
to the given alias. POE::Kernel does this internally, so it's usually
not necessary.
It returns a session reference on success. On failure, it returns undef and sets $! to one of:
ESRCH - The alias does not exist.
Selects are file handle monitors. They generate events to indicate when activity occurs on the file handles they watch. POE keeps track of how many selects are watching a file handle, and it will close the file when nobody is looking at it.
There are three types of select. Each corresponds to one of the bit
vectors in Perl's four-argument select()
function. ``Read'' selects
generate events when files become ready for reading. ``Write'' selects
generate events when files are available to be written to. ``Expedite''
selects generate events when files have out-of-band information to be
read.
The select()
method manipulates all three selects for a file handle at
the same time. Selects are added for each defined state, and selects
are removed for undefined states.
The select_read()
method adds or removes a file handle's read select.
It leaves the other two unchanged.
The select_write()
method adds or removes a file handle's write
select. It leaves the other two unchanged.
The select_expedite()
method adds or removes a file handle's expedite
select. It leaves the other two unchanged.
The POE::Session documentation has more information about _signal events.
POE currently does not make Perl's signals safe. Using signals is
okay in short-lived programs, but long-uptime servers may eventually
dump core if they receive a lot of signals. POE provides a ``safe''
fork()
function that periodically reaps children without using
signals; it emulates the system's SIGCHLD signal for each process in
reaps.
Mileage varies considerably.
The kernel generates _signal events when it receives signals from the operating system. Sessions may also send signals between themselves without involving the OS.
The kernel determines whether or not signals have been handled by looking at _signal states' return values. If the state returns logical true, then it means the signal was handled. If it returns false, then the kernel assumes the signal wasn't handled.
POE will stop sessions that don't handle some signals. These ``terminal'' signals are QUIT, INT, KILL, TERM, HUP, and the fictitious IDLE signal.
POE broadcasts SIGIDLE to all sessions when the kernel runs out of events to dispatch, and when there are no alarms or selects to generate new events.
Finally, there is one fictitious signal that always stops a session: ZOMBIE. If the kernel remains idle after SIGIDLE is broadcast, then SIGZOMBIE is broadcast to force reaping of zombie sessions. This tells these sessions (usually aliased ``daemon'' sessions) that nothing is left to do, and they're as good as dead anyway.
It's normal for aliased sessions to receive IDLE and ZOMBIE when all the sessions that may use them have gone away.
The sig()
method registers a state to handle a particular signal.
Only one state in any given session may be registered for a particular
signal. Registering a second state for the same signal will replace
the previous state with the new one.
Signals that don't have states will be dispatched to the _signal state instead.
The signal()
method posts a signal event to a session. It uses the
kernel's event queue, bypassing the operating system, so the signal's
name is not limited to what the OS allows. For example, the kernel
does something similar to post a fictitious ZOMBIE signal.
$kernel->signal($session, 'BOGUS'); # Not as bogus as it sounds.
POE's signal handling is Perl's signal handling, which means that POE won't safely handle signals as long as Perl has a problem with them.
However, POE works around this in at least SIGCHLD's case by providing
a ``safe'' fork()
function. &POE::Kernel::fork() blocks
$SIG{'CHLD','CLD'} and starts an event loop to poll for expired child
processes. It emulates the system's SIGCHLD behavior by sending a
``soft'' CHLD signal to the appropriate session.
Because POE knows which session called its version of fork(), it can signal just that session that its forked child process has completed.
Note: The first &POE::Kernel::fork call disables POE's usual SIGCHLD handler, so that the poll loop can reap children safely. Mixing plain fork and &POE::Kernel::fork isn't recommended.
The fork()
method tries to fork a process in the usual Unix way. In
addition, it blocks SIGCHLD and/or SIGCLD and starts an event loop to
poll for completed child processes.
POE's fork()
will return different things in scalar and list contexts.
In scalar context, it returns the child PID, 0, or undef, just as
Perl's fork()
does. In a list context, it returns three items: the
child PID (or 0 or undef), the numeric version of $!, and the string
version of $!.
The kernel's state management method lets sessions add, change and remove states at runtime. Wheels use this to add and remove select states from sessions when they're created and destroyed.
The state()
method has three different uses, each for adding, updating
or removing a different kind of state. It manipulates states in the
current session.
The three-parameter version of state()
registers an object or package
state to a method with a different name. Normally the object or
package method would need to be named after the state it catches.
The state()
method returns 1 on success. On failure, it returns 0 and
sets $! to one of:
ESRCH - Somehow, the current session does not exist.
This function can only register or remove one state at a time.
Inline states are manipulated with:
$kernel->state($state_name, $code_reference);
If $code_reference is undef, then $state_name will be removed. Any pending events destined for $state_name will be redirected to _default.
Object states are manipulated with:
$kernel->state($method_name, $object_reference);
If $object_reference is undef, then the $method_name state will be removed. Any pending events destined for $method_name will be redirected to _default.
They can also be maintained with:
$kernel->state($state_name, $object_reference, $object_method);
For example, this maps a session's B®_start¯ state to the object's start_state method:
$kernel->state('_start', $object_reference, 'start_state');
Package states are manipulated with:
$kernel->state($function_name, $package_name);
If $package_name is undef, then the $function_name state will be removed. Any pending events destined for $function_name will be redirected to _default.
POE generates a unique ID for the process, and it maintains unique serial numbers for every session. These functions retrieve various ID values.
Returns a unique ID for this POE process.
my $process_id = $kernel->ID();
Returns a session reference for the given ID. It returns undef if the ID doesn't exist. This allows programs to uniquely identify a particular Session (or detect that it's gone) even if Perl reuses the Session reference later.
Returns an ID for the given POE::Session reference, or undef ith the session doesn't exist.
Perl reuses Session references fairly frequently, but Session IDs are unique. Because of this, the ID of a given reference (stringified, so Perl can release the referenced Session) may appear to change. If it does appear to have changed, then the Session reference is probably invalid.
POE; POE::Session
Oh, probably some.
Please see the POE manpage.
POE::Kernel - POE Event Queue and Resource Manager |