ActiveState!

ActivePerl Documentation
Table of Contents

(Usage Statistics)
(about this ver)


* Getting Started
    * Welcome To ActivePerl
    * Release Notes
    * Readme
    * ActivePerl Change Log
* Install Notes
    * Linux
    * Solaris
    * Windows
* ActivePerl Components
    * Overview
    * PPM
    * Windows Specifics
       * OLE Browser
       * PerlScript
       * Perl for ISAPI
       * PerlEZ
* ActivePerl FAQ
    * Introduction
    * Availability & Install
    * Using PPM
    * Docs & Support
    * Windows Specifics
       * Perl for ISAPI
       * Windows 9X/NT/2000
       * Quirks
       * Web Server Config
       * Web programming
       * Programming
       * Modules & Samples
       * Embedding & Extending
       * Using OLE with Perl
* Windows Scripting
    * Active Server Pages
    * Windows Script Host
    * Windows Script Components

Core Perl Documentation


* perl
* perlfaq
* perltoc
* perlbook

* perlsyn
* perldata
* perlop
* perlreftut
* perldsc
* perllol

* perllexwarn
* perldebug

* perlrun
* perlfunc
* perlopentut
* perlvar
* perlsub
* perlmod
* perlpod

* perlstyle
* perlmodlib
* perlmodinstall
* perltrap
* perlport
* perlsec

* perlref
* perlre
* perlform
* perllocale
* perlunicode

* perlboot
* perltoot
* perltootc
* perlobj
* perlbot
* perltie

* perlipc
* perlnumber
* perlfork
* perlthrtut

* perldiag
* perlfaq1
* perlfaq2
* perlfaq3
* perlfaq4
* perlfaq5
* perlfaq6
* perlfaq7
* perlfaq8
* perlfaq9

* perlcompile

* perlembed
* perlxstut
* perlxs
* perlguts
* perlcall
* perlfilter
* perldbmfilter
* perlapi
* perlintern
* perlapio
* perltodo
* perlhack

* perlhist
* perldelta
* perl5005delta
* perl5004delta

* perlamiga
* perlcygwin
* perldos
* perlhpux
* perlmachten
* perlos2
* perlos390
* perlvms
* perlwin32

Pragmas


* attributes
* attrs
* autouse
* base
* blib
* bytes
* charnames
* constant
* diagnostics
* fields
* filetest
* integer
* less
* lib
* locale
* lwpcook
* open
* ops
* overload
* perllocal
* re
* sigtrap
* strict
* subs
* utf8
* vars
* warnings

Libraries


* ActivePerl
    * DocTools
        * TOC
            * RDF
* AnyDBM_File
* Archive
    * Tar
* AutoLoader
* AutoSplit
* B
    * Asmdata
    * Assembler
    * Bblock
    * Bytecode
    * C
    * CC
    * Debug
    * Deparse
    * Disassembler
    * Lint
    * Showlex
    * Stackobj
    * Terse
    * Xref
* Benchmark
* Bundle
    * LWP
* ByteLoader
* Carp
    * Heavy
* CGI
    * Apache
    * Carp
    * Cookie
    * Fast
    * Pretty
    * Push
    * Switch
* Class
    * Struct
* Compress
    * Zlib
* Config
* CPAN
    * FirstTime
    * Nox
* Cwd
* Data
    * Dumper
* DB
* Devel
    * DProf
    * Peek
    * SelfStubber
* Digest
    * HMAC
    * HMAC_MD5
    * HMAC_SHA1
    * MD2
    * MD5
    * SHA1
* DirHandle
* Dumpvalue
* DynaLoader
* English
* Env
* Errno
* Exporter
    * Heavy
* ExtUtils
    * Command
    * Embed
    * Install
    * Installed
    * Liblist
    * MakeMaker
    * Manifest
    * Miniperl
    * Mkbootstrap
    * Mksymlists
    * MM_Cygwin
    * MM_OS2
    * MM_Unix
    * MM_VMS
    * MM_Win32
    * Packlist
    * testlib
* Fatal
* Fcntl
* File
    * Basename
    * CheckTree
    * Compare
    * Copy
    * CounterFile
    * DosGlob
    * Find
    * Glob
    * Listing
    * Path
    * Spec
        * Functions
        * Mac
        * OS2
        * Unix
        * VMS
        * Win32
    * stat
* FileCache
* FileHandle
* FindBin
* Font
    * AFM
* Getopt
    * Long
    * Std
* HTML
    * AsSubs
    * Element
    * Entities
    * Filter
    * Form
    * FormatPS
    * Formatter
    * FormatText
    * HeadParser
    * LinkExtor
    * Parse
    * Parser
    * TokeParser
    * TreeBuilder
* HTTP
    * Cookies
    * Daemon
    * Date
    * Headers
        * Util
    * Message
    * Negotiate
    * Request
        * Common
    * Response
    * Status
* I18N
    * Collate
* IO
    * Dir
    * File
    * Handle
    * Pipe
    * Poll
    * Seekable
    * Select
    * Socket
        * INET
        * UNIX
* IPC
    * Msg
    * Open2
    * Open3
    * Semaphore
    * SysV
* LWP
    * Debug
    * MediaTypes
    * MemberMixin
    * Protocol
    * RobotUA
    * Simple
    * UserAgent
* Math
    * BigFloat
    * BigInt
    * Complex
    * Trig
* MD5
* MIME
    * Base64
    * QuotedPrint
* NDBM_File
* Net
    * Cmd
    * Config
    * Domain
    * DummyInetd
    * FTP
    * hostent
    * libnetFAQ
    * netent
    * Netrc
    * NNTP
    * PH
    * Ping
    * POP3
    * protoent
    * servent
    * SMTP
    * SNPP
    * Time
* O
* ODBM_File
* Opcode
* Pod
    * Checker
    * Find
    * Html
    * InputObjects
    * Man
    * Parser
    * ParseUtils
    * Plainer
    * Select
    * Text
        * Color
        * Termcap
    * Usage
* POSIX
* PPM
    * SOAPClient
    * SOAPServer
* Safe
* SDBM_File
* Search
    * Dict
* SelectSaver
* SelfLoader
* SHA
* Shell
* SOAP
    * Defs
    * Envelope
    * EnvelopeMaker
    * GenericHashSerializer
    * GenericInputStream
    * GenericScalarSerializer
    * Lite
    * OutputStream
    * Packager
    * Parser
    * Transport
        * HTTP
            * Apache
            * CGI
            * Client
            * Server
        * LOCAL
        * MAILTO
        * POP3
        * TCP
    * TypeMapper
* Socket
* Symbol
* Sys
    * Hostname
    * Syslog
* Term
    * ANSIColor
    * Cap
    * Complete
    * ReadLine
* Test
    * Harness
* Text
    * Abbrev
    * ParseWords
    * Soundex
    * Tabs
    * Wrap
* Thread
    * Queue
    * Semaphore
    * Signal
    * Specific
* Tie
    * Array
    * Handle
    * Hash
    * RefHash
    * Scalar
    * SubstrHash
* Time
    * gmtime
    * Local
    * localtime
    * tm
* UDDI
    * Lite
* UNIVERSAL
* URI
    * data
    * Escape
    * file
    * Heuristic
    * ldap
    * URL
    * WithBase
* User
    * grent
    * pwent
* Win32
    * AuthenticateUser
    * ChangeNotify
    * Clipboard
    * Console
    * Event
    * EventLog
    * File
    * FileSecurity
    * Internet
    * IPC
    * Mutex
    * NetAdmin
    * NetResource
    * ODBC
    * OLE
        * Const
        * Enum
        * NEWS
        * NLS
        * TPJ
        * Variant
    * PerfLib
    * Pipe
    * Process
    * Registry
    * Semaphore
    * Service
    * Sound
    * TieRegistry
* Win32API
    * File
    * Net
    * Registry
* WWW
    * RobotRules
        * AnyDBM_File
* XML
    * Element
    * Parser
        * Expat
    * PPD
    * PPMConfig
    * ValidatingElement
* XSLoader

 POE::Kernel - POE Event Queue and Resource Manager


NAME

POE::Kernel - POE Event Queue and Resource Manager


SUPPORTED PLATFORMS

  • Linux
  • Solaris
  • Windows
This module is not included with the standard ActivePerl distribution. It is available as a separate download using PPM.

SYNOPSIS

  #!/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.


DESCRIPTION

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.


EXPORTED SYMBOLS

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.


PUBLIC KERNEL METHODS

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.

Kernel Management Methods

  • POE::Kernel::run()

    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().

Session Management Methods

  • POE::Kernel::session_create(...)

    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.

Event Management Methods

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( $destination, $state, @args )

    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( $state, @args )

    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( $session, $state, $args )

    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.

Alarm Management Methods

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.

  • POE::Kernel::alarm( $state, $time, @args )

    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.

  • POE::Kernel::delay( $state, $seconds, @args );

    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.

Alias Management Methods

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.

  • POE::Kernel::alias_set( $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.

  • POE::Kernel::alias_remove( $alias )

    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.

  • POE::Kernel::alias_resolve( $alias )

    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.

Select Management Methods

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.

  • POE::Kernel::select( $filehandle, $rd_state, $wr_state, $ex_state )

    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.

  • POE::Kernel::select_read( $filehandle, $read_state )

    The select_read() method adds or removes a file handle's read select. It leaves the other two unchanged.

  • POE::Kernel::select_write( $filehandle, $write_state )

    The select_write() method adds or removes a file handle's write select. It leaves the other two unchanged.

  • POE::Kernel::select_expedite( $filehandle, $expedite_state )

    The select_expedite() method adds or removes a file handle's expedite select. It leaves the other two unchanged.

Signal Management Methods

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.

  • POE::Kernel::sig( $signal_name, $state_name )

    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.

  • POE::Kernel::signal( $session, $signal_name )

    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.

Process Management Methods

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.

  • POE::Kernel::fork( )

    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 $!.

State Management Methods

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.

  • POE::Kernel::state( $state_name, $code_reference ) POE::Kernel::state( $method_name, $object_reference ) POE::Kernel::state( $function_name, $package_name ) POE::Kernel::state( $state_name, $obj_or_package_ref, $method_name )

    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

      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

      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

      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.

ID Management Methods

POE generates a unique ID for the process, and it maintains unique serial numbers for every session. These functions retrieve various ID values.

  • POE::Kernel::ID()

    Returns a unique ID for this POE process.

      my $process_id = $kernel->ID();

  • POE::Kernel::ID_id_to_session( $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.

  • POE::Kernel::ID_session_to_id( $session );

    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.


SEE ALSO

POE; POE::Session


BUGS

Oh, probably some.


AUTHORS & COPYRIGHTS

Please see the POE manpage.

 POE::Kernel - POE Event Queue and Resource Manager