This is Info file pm.info, produced by Makeinfo version 1.68 from the
input file bigpm.texi.


File: pm.info,  Node: Pragmatic,  Next: Proc/Application,  Prev: Pquota,  Up: Module List

Adds pragmata to Exporter
*************************

NAME
====

   Pragmatic - Adds pragmata to Exporter

SYNOPSIS
========

   In module MyModule.pm:

     package MyModule;
     require Pragmatic;
     @ISA = qw (Pragmatic);

     %PRAGMATA = (mypragma => sub {...});

   In other files which wish to use MyModule:

     use MyModule qw (-mypragma); # Execute pragma at import time
     use MyModule qw (-mypragma=1,2,3); # Pass pragma argument list

DESCRIPTION
===========

   Pragmatic implements a default import method for processing pragmata
before passing the rest of the import to Exporter.

   Perl automatically calls the import method when processing a use
statement for a module. Modules and use are documented in *Note Perlfunc:
(perl.info)perlfunc, and *Note Perlmod: (perl.info)perlmod,.

   (Do not confuse Pragmatic with *pragmatic modules*, such as less,
strict and the like.  They are standalone pragmata, and are not associated
with any other module.)

Using Pragmatic Modules
-----------------------

   Using Pragmatic modules is very simple.  To invoke any particular
pragma for a given module, include it in the argument list to use preceded
by a hyphen:

     use MyModule qw (-mypragma);

   `Pragmatic::import' will filter out these arguments, and pass the
remainder of the argument list from the use statement to
`Exporter::import' (actually, to `Exporter::export_to_level' so that
Pragmatic is transparent).

   If you want to pass the pragma arguments, use syntax similar to that of
the -M switch to *perl* (see *Note Perlrun: (perl.info)perlrun,):

     use MyModule qw (-mypragma=abc,1,2,3);

   If there are any warnings or fatal errors, they will appear to come
from the use statement, not from `Pragmatic::import'.

Writing Pragmatic Modules
-------------------------

   Writing Pragmatic modules with Pragmatic is straight-forward.  First,
`require Pragmatic' (you could use it instead, but it exports nothing, so
there is little to gain thereby).  Declare a package global `%PRAGMATA',
the keys of which are the names of the pragmata and their corresponding
values the code references to invoke.  Like this:

     package MyPackage;

     require Pragmatic;

     use strict;
     use vars qw (%PRAGMATA);

     sub something_else { 1; }

     %PRAGMATA =
       (first => sub { print "@_: first\n"; },
        second => sub { $SOME_GLOBAL = 1; },
        third => \&something_else,
        fourth => 'name_of_sub');

   When a pragma is given in a use statement, the leading hyphen is
removed, and the code reference corresponding to that key in `%PRAGMATA',
or a subroutine with the value's name, is invoked with the name of the
package as the first member of the argument list (this is the same as what
happens with import).  Additionally, any arguments given by the caller are
included (see `Using Pragmatic Modules' in this node, above).

EXAMPLES
========

Using Pragmatic Modules
-----------------------

  1. Simple use:
          use MyModule; # no pragmas

          use MyModule qw (-abc); # invoke C<abc>

          use MyModule qw (-p1 -p2); # invoke C<p1>, then C<p2>

  2. Using an argument list:
          use MyModule qw (-abc=1,2,3); # invoke C<abc> with (1, 2, 3)

          use MyModule qw (-p1 -p2=here); # invoke C<p1>, then C<p2>
                                          # with (1, 2, 3)

  3. Mixing with arguments for Exporter: (Please see *Note Exporter:
     Exporter, for a further explanatation.)

          use MyModule ( ); # no pragmas, no exports

          use MyModule qw (fun1 -abc fun2); # import C<fun1>, invoke C<abc>,
                                            # then import C<fun2>

          use MyModule qw (:set1 -abc=3); # import set C<set1>, invoke C<abc>
                                          # with (3)


Writing Pragmatic Modules
-------------------------

  1. Setting a package global:
          %PRAGMATA = (debug => sub { $DEBUG = 1; });

  2. Selecting a method:
          my $fred = sub { 'fred'; };
          my $barney = sub { 'barney'; };

          %PRAGMATA =
            (fred => sub {
               local $^W = 0;
               *flintstone = $fred;
             },

          barney => sub {
            local $^W = 0;
            *flintstone = $barney;
          });

  3. Changing inheritance:
          %PRAGMATA = (super => sub { shift; push @ISA, @_; });

  4. Inheriting pragmata:
          package X;
          @ISA = qw(Pragmatic);
          %PRAGMATA = (debug => 'debug');
          $DEBUG = 0;

          sub debug { ${"$_[0]::DEBUG"} = 1; }

          package Y:
          @ISA = qw(X);
          %PRAGMATA = (debug => 'debug');
          $DEBUG = 0;


SEE ALSO
========

   *Note Exporter: Exporter,

   Exporter does all the heavy-lifting (and is a very interesting module
to study) after Pragmatic has stripped out the pragmata from the use.

DIAGNOSTICS
===========

   The following are the diagnostics generated by Pragmatic.  Items marked
"(W)" are non-fatal (invoke `Carp::carp'); those marked "(F)" are fatal
(invoke `Carp::croak').

No such pragma '%s'
     (F) The caller tried something like "use MyModule (-xxx)" where there
     was no pragma *xxx* defined for MyModule.

Invalid pragma '%s'
     (F) The writer of the called package tried something like "%PRAGMATA =
     (xxx => not_a_sub)" and either assigned *xxx* a non-code reference,
     or *xxx* is not a method in that package.

Pragma '%s' failed
     (W) The pramga returned a false value.  The module is possibly in an
     inconsisten state after this.  Proceed with caution.

AUTHORS
=======

   B. K. Oxley (binkley) at Home <binkley@bigfoot.com>

COPYRIGHT
=========

     Copyright 1999, B. K. Oxley.

   This library is free software; you may redistribute it and/or modify it
under the same terms as Perl itself.


File: pm.info,  Node: Proc/Application,  Next: Proc/Application/Daemon,  Prev: Pragmatic,  Up: Module List

base class for all applications
*******************************

NAME
====

   Proc::Application - base class for all applications

SYNOPSIS
========

     package Program;
     @Program::ISA = qw(Proc::Application);
     sub main { print "Done\n"; }
     package main;
     Program->new->run();

DESCRIPTION
===========

   This is a application code base

new
---

main
----

run
---

DESTROY
-------

processCommandOptions
---------------------

   Process options from command line by Getopt::Long && Getopt::ArgvFile

log
---

   Create and return log object ( the Log::Dispatch )

options
-------

description
-----------

usage
-----

_processFileLog
---------------

_processSysLog
--------------

_processScreenLog
-----------------

_processFileLock
----------------

stFormatLogLine
---------------

detach
------

chroot
------

changeUser
----------

changeGroup
-----------

pidfile
-------


File: pm.info,  Node: Proc/Application/Daemon,  Next: Proc/Background,  Prev: Proc/Application,  Up: Module List

daemon class based on Proc::Application;
****************************************

NAME
====

   Proc::Application::Daemon - daemon class based on Proc::Application;

SYNOPSIS
========

     package Program;
     use Proc::Application::Daemon;
     use base qw(Proc::Application::Daemon);
     sub handler
     {
         my ( $his, $clientSocket ) = @_;
         $this->socket->print ( 'Done' );
         $this->log->warning ( 'warning' );
         die "Error";
     }
     package main;
     Program->new->run();

DESCRIPTION
===========

   daemon class based on Proc::Application;

new
---

   A construtror, setup childs and childCount

options
-------

   Add mode (fork|single|prefork=[count]) and socket
(domain=unix|inet|ssl:all_io::socket:: parameter) options

processSocketCreate
-------------------

   Handler for socket option. Create new socket and store it to
$object->{socket}

processModeParameter
--------------------

   Child for 'prefork=count' mode and setup preforkCount option

socket
------

   Return a client socket from $object->{socket}

mainSocket
----------

   Return a main daemon socket from $object->{socket}

done
----

   You must return 'true' for end main loop

mainHandler
-----------

   Call handler() method with $cliendSocket atrument, log the errors of
execution and close client socket at exit

handler
-------

   Real work method, get $this and $clientSocket argumentds.

childs
------

   Return a hash reference of childs with keys with pids

processSigChild
---------------

   SIGCHLD processor. Get a child pid by waitpid() and delete it from
childs()

forkFunction
------------

   Get three code refs ( for run at parent, child and error fork
sitiations ), fork process and execute parameters functions. Store pid of
new process at childs(), exit(0) at child after execute of child function,
log fork error and sleep(1) after fork error.  funtions

threadFunction
--------------

realMain
--------

   Main loop. accept() the new connection, and fork (if fork more) and
pass execution to mainHandler

main
----

   Prefork processes if prefork mode, loop up for preforked childs count
and call realMain()

DESTROY
-------

   Send TERM signal to all childs and call parent DESTROY()

Log Debug Error Fatal Run Options
---------------------------------

   for compatibility with Net::Daemon


File: pm.info,  Node: Proc/Background,  Next: Proc/Background/Unix,  Prev: Proc/Application/Daemon,  Up: Module List

Generic interface to Unix and Win32 background process management
*****************************************************************

NAME
====

   Proc::Background - Generic interface to Unix and Win32 background
process management

SYNOPSIS
========

     use Proc::Background;
     timeout_system($seconds, $command, $arg1);
     timeout_system($seconds, "$command $arg1");
     my $proc1 = Proc::Background->new($command, $arg1, $arg2);
     my $proc2 = Proc::Background->new("$command $arg1 1>&2");
     $proc1->alive;
     $proc1->die;
     $proc1->wait;
     my $time1 = $proc1->start_time;
     my $time2 = $proc1->end_time;

DESCRIPTION
===========

   This is a generic interface for placing processes in background on both
Unix and Win32 platforms.  This module lets you start, kill, wait on,
retrieve exit values, and see if background processes still exist.

METHODS
=======

new command, [*arg*, [*arg*, ...]]
new 'command [*arg* [*arg* ...]]'
     This creates a new background process.  As exec() or system() may be
     passed an array with a single single string element containing a
     command to be passed to the shell or an array with more than one
     element to be run without calling the shell, new has the same
     behavior.

     In certain cases new will attempt to find command on the system and
     fail if it cannot be found.

     For Win32 operating systems:

          The Win32::Process module is always used to spawn background
          processes on the Win32 platform.  This module always takes a
          single string argument containing the executable's name and
          any option arguments.  In addition, it requires that the
          absolute path to the executable is also passed to it.  If
          only a single argument is passed to new, then it is split on
          whitespace into an array and the first element of the split
          array is used at the executable's name.  If multiple
          arguments are passed to new, then the first element is used
          as the executable's name.

          If the executable's name is an absolute path, then new
          checks to see if the executable exists in the given location
          or fails otherwise.  If the executable's name is not
          absolute, then the executable is searched for using the PATH
          environmental variable.  The input executable name is always
          replaced with the absolute path determined by this process.

          In addition, when searching for the executable, the
          executable is searched for using the unchanged executable
          name and if that is not found, then it is checked by
          appending `.exe' to the name in case the name was passed
          without the `.exe' suffix.

          Finally, the argument array is placed back into a single
          string and passed to Win32::Process::Create.

     For non-Win32 operating systems, such as Unix:

          If more than one argument is passed to new, then new
          assumes that the command will not be passed through the
          shell and the first argument is the executable's relative
          or absolute path.  If the first argument is an absolute
          path, then it is checked to see if it exists and can be
          run, otherwise new fails.  If the path is not absolute,
          then the PATH environmental variable is checked to see if
          the executable can be found.  If the executable cannot be
          found, then new fails.  These steps are taking to prevent
          exec() from failing after an fork() without the caller of
          new knowing that something failed.

     If anything fails, then new returns an empty list in a list context,
     an undefined value in a scalar context, or nothing in a void context.

pid
     Returns the process ID of the created process.  This value is saved
     even if the process has already finished.

alive
     Return 1 if the process is still active, 0 otherwise.

die
     Reliably try to kill the process.  Returns 1 if the process no longer
     exists once die has completed, 0 otherwise.  This will also return 1
     if the process has already died.  On Unix, the following signals are
     sent to the process in one second intervals until the process dies:
     HUP, QUIT, INT, KILL.

wait
     Wait for the process to exit.  Return the exit status of the command
     as returned by wait() on the system.  To get the actual exit value,
     divide by 256 or right bit shift by 8, regardless of the operating
     system being used.  If the process never existed, then return an empty
     list in a list context, an undefined value in a scalar context, or
     nothing in a void context.  This function may be called multiple times
     even after the process has exited and it will return the same exit
     status.

start_time
     Return the value that the Perl function time() returned when the
     process was started.

end_time
     Return the value that the Perl function time() returned when the exit
     status was obtained from the process.

FUNCTIONS
=========

timeout_system timeout, command, [*arg*, [*arg*...]]
timeout_system 'timeout command [*arg* [*arg*...]]'
     Run a command for timeout seconds and if the process did not exit,
     then kill it.  While the timeout is implemented using sleep(), this
     function makes sure that the full timeout is reached before killing
     the process.  timeout_system does not wait for the complete timeout
     number of seconds before checking if the process has exited.  Rather,
     it sleeps repeatidly for 1 second and checks to see if the process
     still exists.

     In a scalar context, timeout_system returns the exit status from the
     process.  In an array context, timeout_system returns a two element
     array, where the first element is the exist status from the process
     and the second is set to 1 if the process was killed by
     timeout_system or 0 if the process exited by itself.

     The exit status is the value returned from the wait() call.  If the
     process was killed, then the return value will include the killing of
     it.  To get the actual exit value, divide by 256.

     If something failed in the creation of the process, the subroutine
     returns an empty list in a list context, an undefined value in a
     scalar context, or nothing in a void context.

IMPLEMENTATION
==============

   *Proc::Background* comes with two modules, *Proc::Background::Unix* and
*Proc::Background::Win32*.  Currently, on the Unix platform
*Proc::Background* it uses the *Proc::Background::Unix* class and on the
Win32 platform *Proc::Win32*, which makes use of *Win32::Process*, is used.

   The *Proc::Background* assigns to @ISA either *Proc::Unix* or
*Proc::Win32*, which does the OS dependent work.  The OS independent work
is done in *Proc::Background*.

   Proc::Background uses two variables to keep track of the process.
$self->{_os_obj} contains the operating system object to reference the
process.  On a Unix systems this is the process id (pid).  On Win32, it is
an object returned from the *Win32::Process* class.  When $self->{_os_obj}
exists, then the process is running.  When the process dies, this is
recorded by deleting $self->{_os_obj} and saving the exit value
$self->{_exit_value}.

   Anytime alive is called, a waitpid() is called on the process and the
return status, if any, is gathered and saved for a call to wait.  This
module does not install a signal handler for SIGCHLD.  If for some reason,
the user has installed a signal handler for SIGCHLD, then, then when this
module calls waitpid(), the failure will be noticed and taken as the
exited child, but it won't be able to gather the exit status.  In this
case, the exit status will be set to 0.

SEE ALSO
========

   See also the *Note Proc/Background/Unix: Proc/Background/Unix, and
*Note Proc/Background/Win32: Proc/Background/Win32, manual pages.

AUTHOR
======

   Blair Zajac <blair@gps.caltech.edu>

COPYRIGHT
=========

   Copyright (C) 1998-2001 Blair Zajac.  All rights reserved.  This
package is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.


File: pm.info,  Node: Proc/Background/Unix,  Next: Proc/Background/Win32,  Prev: Proc/Background,  Up: Module List

Unix interface to process mangement
***********************************

NAME
====

   Proc::Background::Unix - Unix interface to process mangement

SYNOPSIS
========

   Do not use this module directly.

DESCRIPTION
===========

   This is a process management class designed specifically for Unix
operating systems.  It is not meant used except through the
*Proc::Background* class.  See *Note Proc/Background: Proc/Background, for
more information.

AUTHOR
======

   Blair Zajac <blair@gps.caltech.edu>

COPYRIGHT
=========

   Copyright (C) 1998-2001 Blair Zajac.  All rights reserved.  This
package is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.


File: pm.info,  Node: Proc/Background/Win32,  Next: Proc/Daemon,  Prev: Proc/Background/Unix,  Up: Module List

Interface to process mangement on Win32 systems
***********************************************

NAME
====

   Proc::Background::Win32 - Interface to process mangement on Win32
systems

SYNOPSIS
========

   Do not use this module directly.

DESCRIPTION
===========

   This is a process management class designed specifically for Win32
operating systems.  It is not meant used except through the
*Proc::Background* class.  See *Note Proc/Background: Proc/Background, for
more information.

IMPLEMENTATION
==============

   This package uses the Win32::Process class to manage the objects.

AUTHOR
======

   Blair Zajac <blair@gps.caltech.edu>

COPYRIGHT
=========

   Copyright (C) 1998-2001 Blair Zajac.  All rights reserved.  This
package is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.


File: pm.info,  Node: Proc/Daemon,  Next: Proc/Forkfunc,  Prev: Proc/Background/Win32,  Up: Module List

Run Perl program as a daemon process
************************************

NAME
====

   Proc::Daemon - Run Perl program as a daemon process

SYNOPSIS
========

     use Proc::Daemon;
     Proc::Daemon::Init;

DESCRIPTION
===========

   This module contains the routine Init which can be called by a perl
program to initialize itself as a daemon.  A daemon is a process that runs
in the background with no controlling terminal.  Generally servers (like
FTP and HTTP servers) run as daemon processes.  However, do not make the
mistake that a daemon == server.

   The *Proc::Daemon::Init* function does the following:

  1. Forks a child and exits the parent process.

  2. Becomes a session leader (which detaches the program from the
     controlling terminal).

  3. Forks another child process and exits first child.  This prevents the
     potential of acquiring a controlling terminal.

  4. Changes the current working directory to "/".

  5. Clears the file creation mask.

  6. Closes all open file descriptors.

        You will notice that no logging facility, or other functionality
is performed.  *Proc::Daemon::Init* just performs the main steps to
initialize a program as daemon.  Since other funtionality can vary
depending on the nature of the program, *Proc::Daemon* leaves the
implementation of other desired functionality to the caller, or other
module/library (like Sys::Syslog).

   There is no meaningful return value *Proc::Daemon::Init*.  If an error
occurs in Init so it cannot perform the above steps, than it croaks with
an error message.  One can prevent program termination by using eval.

OTHER FUNCTIONS
===============

   *Proc::Daemon* also defines some other functions.  These functions can
be imported into the callers name space if the function names are
specified during the use declaration:

Fork
----

   Fork is like the built-in fork, but will try to fork if at all
possible, retrying if necessary.  If not possible, Fork will croak.

OpenMax
-------

   OpenMax returns the maximum file descriptor number.  If undetermined,
64 will be returned.

NOTES
=====

   * *Proc::Daemon::init* is still available for backwards capatibilty.
     However, it will not perform the double fork, and will return the
     session ID.

AUTHOR
======

   Earl Hood, earlhood@usa.net

   http://www.oac.uci.edu/indiv/ehood/

CREDITS
=======

   Implementation of *Proc::Daemon* derived from the following sources:

   * *Advanced Programming in the UNIX Environment*, by W. Richard Stevens.
     Addison-Wesley, Copyright 1992.

   * *UNIX Network Progamming*, Vol 1, by W. Richard Stevens.
     Prentice-Hall PTR, Copyright 1998.

DEPENDENCIES
============

   *Proc::Daemon* depends on the following modules: Carp, POSIX.

SEE ALSO
========

   *Note POSIX: POSIX,, *Note Sys/Syslog: Sys/Syslog,


File: pm.info,  Node: Proc/Forkfunc,  Next: Proc/Killall,  Prev: Proc/Daemon,  Up: Module List

fork off a function
*******************

NAME
====

   Proc::Forkfunk - fork off a function

SYNOPSIS
========

     use Proc::Forkfunc;

     forkfunc(\&child_func,@child_args);

DESCRIPTION
===========

   Fork off a process.  Call a function on the child process the function
should be passed in as a reference.  The child function should not return.

   Logic copied from somewhere, probably Larry Wall.

AUTHOR
======

   David Muir Sharnoff <muir@idiom.com>


File: pm.info,  Node: Proc/Killall,  Next: Proc/Killfam,  Prev: Proc/Forkfunc,  Up: Module List

Kill all instances of a process by pattern matching the command-line
********************************************************************

NAME
====

   killall - Kill all instances of a process by pattern matching the
command-line

SYNOPSIS
========

     use Proc::Killall;

     killall('HUP', 'xterm'); # SIGHUP all xterms
     killall('KILL', '^netscape$'); # SIGKILL to "netscape"

DESCRIPTION
===========

   This module provides one function, `killall()', which takes two
parameters: a signal name or number (see kill()) and a process pattern.
This pattern is matched against the process' command-line as the `ps'
command would show it (`ps' is not used internally, instead a package
called `Proc::ProcessTable' is used).

   `killall' searches the process table and sends that signal to all
processes which match the pattern. The return value is the number of
processes that were succesfully signaled. If any kills failed, the $!
variable will be set based on that last one that failed (even if a
successful kill happened afterward).

AUTHOR
======

   Written in 2000 by Aaron Sherman <ajs@ajs.com>

   `Proc::Killall' is copyright 2000 by Aaron Sherman, and may be
distributed under the same terms as Perl itself.

PREREQUISITES
=============

   `Proc::ProcessTable' is required for `Proc::Killall' to function.

SEE ALSO
========

   *Note Perl: (perl.info)perl,, *Note Perlfunc: (perl.info)perlfunc,,
*Note Perlvar: (perl.info)perlvar,, *Note Proc/ProcessTable:
Proc/ProcessTable,


File: pm.info,  Node: Proc/Killfam,  Next: Proc/Lock,  Prev: Proc/Killall,  Up: Module List

kill a list of pids, and all their sub-children
***********************************************

NAME
====

   Proc::Killfam - kill a list of pids, and all their sub-children

SYNOPSIS
========

     use Proc::Kilfam;
     killfam $signal, @pids;

DESCRIPTION
===========

   *killfam* accepts the same arguments as the Perl builtin kill command,
but, additionally, recursively searches the process table for children and
kills them as well.

EXAMPLE
=======

   *killfam 'TERM', ($pid1, $pid2, @more_pids)*;

KEYWORDS
========

   kill, signal


File: pm.info,  Node: Proc/Lock,  Next: Proc/Lock/File,  Prev: Proc/Killfam,  Up: Module List

lock interface module
*********************

NAME
====

   Proc::Lock - lock interface module

SYNOPSIS
========

     use Proc::Lock;
     my $lock = new Proc::Lock ( ... );
     $lock->set ();
     die "locked" if $lock->isSet ();
     $lock->unset ();

DESCRIPTION
===========

     Generic lock module. You must subclass this class and overwrite set, unset, isSet and new (possible) for do your work

new
---

   Construct new lock object. You can setup parameters:

   ProcessName => $name of process for make lock file name Pid         =>
$ pid of process for make lock file name HostName    => $ name of host for
make lock file name Wait        => wait for lock is clean and continue
Timeout     => limit of time of wait of lock clean NoUnset     => not
unset lock at unset operation

     my $lock = new Proc::Lock... ( ProcessName => $0,
                                    Pid         => $$,
                                    Hostname    => gethostname(),
                                    Wait        => 1,
     				NoUnset     => 1,
                                    Timeout     => 30 );

     $lock->set || die "already runned";

set
---

   setup lock. Return true if success

unset
-----

   unset lock, return true if success

isSet
-----

   return true if lock is up

DESTROY
-------

   destroy lock object

log
---

   Return log object

_set _unset _isSet
------------------

   private methods, You must put your functionality to this methods.  The
real methods ( set, unset, isSet ) call this method.


File: pm.info,  Node: Proc/Lock/File,  Next: Proc/PID_File,  Prev: Proc/Lock,  Up: Module List

lock interface module
*********************

NAME
====

   Proc::Lock::File - lock interface module

SYNOPSIS
========

     use Proc::Lock::File;
     my $lock = new Proc::Lock::File ( Directory => '/var/locks',
     				   ProcessName => 'locker' );
     $lock->set () || die "already locked";
     die "locked" if $lock->isSet ();
     $lock->unset ();

DESCRIPTION
===========

     Generic lock module. You must subclass this class and overwrite set, clear, isSet and new (possible) for do your work

new
---

   Construct new file lock object. Add Directory parameter to parent
constructor.


File: pm.info,  Node: Proc/PID_File,  Next: Proc/ProcessTable,  Prev: Proc/Lock/File,  Up: Module List

check whether a self process is already running
***********************************************

NAME
====

   Proc::PID_File - check whether a self process is already running

SYNOPSIS
========

     use Proc::PID_File;

     $Pid_File = Proc::PID_File->new(path=>"/var/run/mydaemon.pid");
     if (!$Pid_File->init)  { die "Can't open/create pid file: $!" }
     if ($Pid_File->active) { die "mydaemon is already running" }

     # go ahead, daemonize...

DESCRIPTION
===========

   A pid file is a file that contain, guess what, pid. Pids are written
down to files so that:

   * a program can know whether an instance of itself is currently running

   * other processes can know the pid of a running program

   This module can be used so that your script can do the former.

   If a pid file is created by the init() method, it will be automatically
deleted when the object is destroyed.

AUTHOR
======

   Copyright (C) 2000, Steven Haryanto <steven@haryan.to>. All rights
reserved.

   This module is free software; you may redistribute it and/or modify it
under the same terms as Perl itself.

HISTORY
=======

   000731 - first hack


File: pm.info,  Node: Proc/ProcessTable,  Next: Proc/ProcessTable/Process,  Prev: Proc/PID_File,  Up: Module List

Perl extension to access the unix process table
***********************************************

NAME
====

   Proc::ProcessTable - Perl extension to access the unix process table

SYNOPSIS
========

     use ProcessTable;

     $p = new Proc::ProcessTable( 'cache_ttys' => 1 );
     @fields = $p->fields;
     $ref = $p->table;

DESCRIPTION
===========

   Perl interface to the unix process table.

METHODS
=======

new
     Creates a new ProcessTable object. The constructor can take one flag:

     cache_ttys - causes the constructor to look for and use a file that
     caches a mapping of tty names to device numbers, and to create the
     file if it doesn't exist (this file is /tmp/TTYDEVS by default). This
     feature requires the Storable module.

fields
     Returns a list of the field names supported by the module on the
     current architecture.

table
     Reads the process table and returns a reference to an array of
     Proc::ProcessTable::Process objects. Attributes of a process object
     are returned by accessors named for the attribute; for example, to get
     the uid of a process just do:

     $process->uid

     The priority and pgrp methods also allow values to be set, since these
     are supported directly by internal perl functions.

EXAMPLES
========

     # A cheap and sleazy version of ps
     use Proc::ProcessTable;

     $FORMAT = "%-6s %-10s %-8s %-24s %s\n";
     $t = new Proc::ProcessTable;
     printf($FORMAT, "PID", "TTY", "STAT", "START", "COMMAND");
     foreach $p ( @{$t->table} ){
       printf($FORMAT,
              $p->pid,
              $p->ttydev,
              $p->state,
              scalar(localtime($p->start)),
              $p->cmndline);
     }

     # Dump all the information in the current process table
     use Proc::ProcessTable;

     $t = new Proc::ProcessTable;

     foreach $p (@{$t->table}) {
      print "--------------------------------\n";
      foreach $f ($t->fields){
        print $f, ":  ", $p->{$f}, "\n";
      }
     }

CAVEATS
=======

   Please see the file README in the distribution for a list of supported
operating systems. Please see the file PORTING for information on how to
help make this work on your OS.

AUTHOR
======

   D. Urist, durist@world.std.com

SEE ALSO
========

   Proc::ProcessTable::Process.pm, perl(1).


File: pm.info,  Node: Proc/ProcessTable/Process,  Next: Proc/SafePipe,  Prev: Proc/ProcessTable,  Up: Module List

Perl process objects
********************

NAME
====

   Proc::ProcessTable::Process - Perl process objects

SYNOPSIS
========

     $process->kill(9);
     $process->priority(19);
     $process->pgrp(500);
     $uid = $process->uid;
     ...

DESCRIPTION
===========

   This is a stub module to provide OO process attribute access for
Proc::ProcessTable. Proc::ProcessTable::Process objects are constructed
directly by Proc::ProcessTable; there is no constructor method, only
accessors.

METHODS
=======

kill
     Sends a signal to the process; just an aesthetic wrapper for perl's
     kill. Takes the signal (name or number) as an argument. Returns number
     of processes signalled.

priority
     Get/set accessor; if called with a numeric argument, attempts to reset
     the process's priority to that number using perl's <B>setpriority
     function. Returns the process priority.

pgrp
     Same as above for the process group.

all other methods...
     are simple accessors that retrieve the process attributes for which
     they are named. Currently supported are:

          uid         UID of process
          gid         GID of process
          euid        effective UID of process           (Solaris only)
          egid        effective GID of process           (Solaris only)
          pid         process ID
          ppid        parent process ID
          spid        sprod ID                           (IRIX only)
          pgrp        process group
          sess        session ID
          cpuid       CPU ID of processor running on     (IRIX only)
          priority    priority of process
          ttynum      tty number of process
          flags       flags of process
          minflt      minor page faults                  (Linux only)
          cminflt     child minor page faults            (Linux only)
          majflt      major page faults                  (Linux only)
          cmajflt     child major page faults            (Linux only)
          utime       user mode time (1/100s of seconds) (Linux only)
          stime       kernel mode time                   (Linux only)
          cutime      child utime                        (Linux only)
          cstime      child stime                        (Linux only)
          time        user + system time
          ctime       child user + system time
          timensec    user + system nanoseconds part	 (Solaris only)
          ctimensec   child user + system nanoseconds    (Solaris only)
          qtime       cumulative cpu time                (IRIX only)
          size        virtual memory size (bytes)
          rss         resident set size (bytes)
          wchan       address of current system call
          fname       file name
          start       start time (seconds since the epoch)
          pctcpu      percent cpu used since process started
          state       state of process
          pctmem      percent memory
          cmndline    full command line of process
          ttydev      path of process's tty
          clname      scheduling class name              (IRIX only)

     See the "README.osname" files in the distribution for more up-to-date
     information.

AUTHOR
======

   D. Urist, durist@world.std.com

SEE ALSO
========

   Proc::ProcessTable.pm, perl(1).


File: pm.info,  Node: Proc/SafePipe,  Next: Proc/Scoreboard,  Prev: Proc/ProcessTable/Process,  Up: Module List

popen() and " without calling the shell
***************************************

NAME
====

   Proc::SafePipe - popen() and " without calling the shell

SYNOPSIS
========

     $fh		= popen_noshell 'r', 'decrypt', $input;
     ($fh, $pid)	= popen_noshell 'w', 'ssh', $host, "cat >$output";

     $all_output	= backtick_noshell 'decrypt', $input;
     @lines	= backtick_noshell $cmd, @arg;

DESCRIPTION
===========

   These functions provide a simple way to read from or write to commands
which are run without being interpreted by the shell.  They croak if
there's a system failure, such as a failed fork.

popen_noshell mode command [*arg*]...
     This function is similar to popen() except that the command and its
     related *arg*s are never interpreted by a shell, they are passed to
     exec() as-is.  The mode argument must be `'r'' or 'w'.

     If called in an array context the return value is a list consisting of
     the filehandle and the PID of the child.  In a scalar context only the
     filehandle is returned.

backtick_noshell command [*arg*]...
     This function runs the given command with the given *arg*s and
     returns the output, like ```' does.  The difference is that the
     arguments are not filtered through a shell, they are exec()ed
     directly.

     The return value is either all the output from the command (if in a
     scalar context) or a list of the lines gathered from the command (in
     an array context).  The exit status of the command is in $?.

AUTHOR
======

   Roderick Schertler <`roderick@argon.org'>


File: pm.info,  Node: Proc/Scoreboard,  Next: Proc/Scoreboard/Dir,  Prev: Proc/SafePipe,  Up: Module List

interface scoreboard class
**************************

NAME
====

   Proc::Scoreboard - interface scoreboard class

SYNOPSIS
========

     use Proc::Scoreboard;
     my $scoreboard = new Proc::Scoreboard ( ... );
     my @idList = $scoreboard->list ();
     $scoreboard->add    ( $id );
     $scoreboard->delete ( $id );
     $scoreboard->modify ( $id, %hash );

DESCRIPTION
===========

   Intertface class for scoreboard.

new
---

   The constructor

add
---

     $sb->add ( $id );

   add new board with id $id to scoreboard

delete
------

     $sb->delete ( $id );

   delete board with id $id from scoreboard

modify
------

     $db->modify ( $id, %hash );

   modify board with id $id by passed parameters

list
----

   return list of all known scoreboards id's


File: pm.info,  Node: Proc/Scoreboard/Dir,  Next: Proc/Short,  Prev: Proc/Scoreboard,  Up: Module List

interface scoreboard class
**************************

NAME
====

   Proc::Scoreboard - interface scoreboard class

SYNOPSIS
========

     use Proc::Scoreboard::Dir;
     my $scoreboard = new Proc::Scoreboard ( Directory => '/var/scoreboard' );
     my @idList = $scoreboard->list ();
     $scoreboard->add    ( $pid );
     $scoreboard->delete ( $pid );
     $scoreboard->modify ( $pid, %hash );

DESCRIPTION
===========

   Intertface class for scoreboard.

new
---

   The constructor

add
---

     $sb->add ( $id );

   add new board with id $id to scoreboard

delete
------

     $sb->delete ( $id );

   delete board with id $id from scoreboard

modify
------

     $db->modify ( $id, %hash );

   modify board with id $id by passed parameters

list
----

   return list of all known scoreboards id's


File: pm.info,  Node: Proc/Short,  Next: Proc/Simple,  Prev: Proc/Scoreboard/Dir,  Up: Module List

return short system calls with options
**************************************

NAME
====

   Proc::Short - return short system calls with options

SYNOPSIS
========

     use Proc::Short;

     $myproc = Proc::Short->new();  # create a new process object

     # settings below represent defaults
     $myproc->maxtime(300);         # set final timeout after 5 minutes
     $myproc->num_tries(5);         # try 5 times at most
     $myproc->time_per_try(30);     # time per try 30 sec
     $myproc->time_btw_tries(5);    # time between tries 5 sec

     # additional options
     $myproc->accept_no_error();    # Re-try if any STDERR output
     $myproc->pattern_stdout($pat); # require STDOUT to match regex $pat
     $myproc->pattern_stderr($pat); # require STDERR to match regex $pat
     $myproc->allow_shell(0);       # never use shell for operation
     $myproc->allow_shell(1);       # allowed to use shell for op

     $myproc->run("shell-command-line"); # Launch a shell process
     $myproc->run(sub { ... });          # Launch a perl subroutine
     $myproc->run(\&subroutine);         # Launch a perl subroutine

     Proc::Short::debug($level);         # Turn debug on

DESCRIPTION
===========

   The Proc::Short is intended to be an extension of the backticks
operator in PERL which incorporates a number of options, including
collecting STDOUT and STDERR separately - plus timeout and automatic
retries.  A new process object is created by

     $myproc = Proc::Short->new();

   The default will timeout after 30 seconds (timeout) for each attempt,
will try a process up to 10 times, with 5 seconds between each try.
Either shell-like command lines or references to perl subroutines can be
specified for launching a process in background.  A simple list process,
for example, can be started via the shell as

     ($out, $in) = $myproc->run("ls");

   or, as a perl subroutine, with

     $myproc->run(sub { return <*>; });

   The run Method will try to run the named process.  If the process times
out (after time_per_try seconds) or has a error defined as unacceptable,
it will wait (for time_btw_tries seconds) and try again.  This can repeat
until *maxtime* seconds or num_tries tries of the process to be run.

   The user can specify what constitutes an unacceptable error of STDOUT
or STDERR output - i.e. demanding a retry.  One common shorthand is to
have the run method retry if there is any return from STDERR.

     $myproc->accept_no_error();    # Re-try if any STDERR
     $myproc->pattern_stdout($pat); # require STDOUT to match regex $pat
     $myproc->pattern_stderr($pat); # require STDERR to match regex $pat

METHODS
=======

   The following methods are available:

new (Constructor)
     Create a new instance of this class by writing either

          $proc = new Proc::Short;   or   $proc = Proc::Short->new();

     The new method takes no arguments.

findexec
     Find where the named executables are in the path, or die if any are
     not found.

          ($fullpath) = $proc->needexec("ssh");

     The *needexec* method ...

unixhelp
     Try various ways to get help on a given executable.

          ($helpmsg) = $proc->unixhelp("ssh");

unixversion
     Try various ways to get version number on a given executable.

          ($helpmsg) = $proc->unixhelp("ssh");

run
     Run a new process and collect the standard output and standard error
     via separate pipes.  By default, it forks off another process and
     collects the output when it is done.  There is a time limit of

          ($out, $err, $status) = $proc->run("program-name");

     There are a number of options.  You can start execution of an
     independent Perl function (like "eval" except with timeout, retries,
     etc.).  Simply provide the function reference like

          ($out, $err, $status) = $proc->run(\&perl_function);

     or supply an unnamed subroutine:

          ($out, $err, $status) = $proc->run( sub { sleep(1) } );

     The run Method returns after the the function finishes, one way or
     another.

num_tries Return or set the maximum number of tries the run method will  attempt an operation if there are unallowed errors.  Default is 5.  =cut
time_per_try Return or set the maximum time in seconds for each attempt which  run makes of an operation.  Multiple tries in case of error  can go longer than this.  Default is 30 seconds.  =cut
time_btw_tries Return or set the time in seconds between attempted operations  in case of unacceptable error.  Default is 5 seconds.   =cut
     sub AUTOLOAD {     my $self= shift;     my $type= ref($self) or
     croak("$self is not an object");     my $name= $AUTOLOAD;     $name
     =~ s/.*://; # strip qualified call, i.e. Geometry::that     unless
     (exists $self->{$name}) { 	croak("Can't access `$name' field
     in object of class $type");     }     if (@_) { 	my $val= @_; 	if
     (defined($intdefaults{$name}) and not ($val =~ /\d+/)) {
     croak "Invalid $name initializer $val"; 	} 	$self->{$name}=
     $val;     }     return $self->{$name}; }

     ######################################################################
     # Internal debug print function
     ######################################################################
     sub _dprt {     return unless $Debug;     if (ref($_[0])) {
     warn ref(shift()), "> @_\n";     } else { 	warn "> @_\n";     }
     }

     ######################################################################
     # This is for getting the WNOHANG constant of the system: a magic #
     flag for the "waitpid" command which guards against certain errors #
     which could hang the system.  # # Since the waitpid(-1, &WNOHANG)
     command isn't supported on all Unix # systems, and we still want
     Proc::Short to run on every system, we # have to quietly perform some
     tests to figure out if - or if not.  # The function returns the
     constant, or undef if it's not available.
     ######################################################################
     sub _get_system_nohang {     my $nohang;     open(SAVEERR,
     ">&STDERR");     # If the system doesn't even know /dev/null, forget
     about it.      open(STDERR, ">/dev/null") || return undef;     #
     Close stderr, since some weirdo POSIX modules write nasty     # error
     messages     close(STDERR);     # Check for the constant     eval
     'use POSIX ":sys_wait_h"; $nohang = &WNOHANG;';     # Re-open STDERR
       open(STDERR, ">&SAVEERR");     close(SAVEERR);     # If there was
     an error, return undef     return undef if $@;     return $nohang; }

     1;

     __END__

NOTE
====

   This is an attempt to duplicate the ease of use of backticks (") while
allowing additional options like timeout or re-tries in case of error.

Requirements
============

   I'd recommend using at least perl 5.003 - if you don't have it, this is
the time to upgrade! Get 5.005_02 or better.

AUTHORS
=======

   John Hanju Kim <jhkim@fnal.gov>


File: pm.info,  Node: Proc/Simple,  Next: Proc/SyncExec,  Prev: Proc/Short,  Up: Module List

launch and control background processes
***************************************

NAME
====

   Proc::Simple - launch and control background processes

SYNOPSIS
========

     use Proc::Simple;

     $myproc = Proc::Simple->new();        # Create a new process object

     $myproc->start("shell-command-line"); # Launch a shell process
     $myproc->start(sub { ... });          # Launch a perl subroutine
     $myproc->start(\&subroutine);         # Launch a perl subroutine

     $running = $myproc->poll();           # Poll Running Process

     $proc->kill_on_destroy(1);            # Set kill on destroy
     $proc->signal_on_destroy("KILL");     # Specify signal to be sent
                                           # on destroy

     $myproc->kill();                      # Kill Process (SIGTERM)

     $myproc->kill("SIGUSR1");             # Send specified signal

     $myproc->exit_status();               # Return exit status of process

     Proc::Simple::debug($level);          # Turn debug on

DESCRIPTION
===========

   The Proc::Simple package provides objects that model real-life
processes from a user's point of view. A new process object is created by

     $myproc = Proc::Simple->new();

   Either shell-like command lines or references to perl subroutines can
be specified for launching a process in background.  A 10-second sleep
process, for example, can be started via the shell as

     $myproc->start("sleep 10");

   or, as a perl subroutine, with

     $myproc->start(sub { sleep(10); });

   The start Method returns immediately after starting the specified
process in background, i.e. non-blocking mode.  It returns 1 if the
process has been launched sucessfully and 0 if not.

   The poll method checks if the process is still running

     $running = $myproc->poll();

   and returns 1 if it is, 0 if it's not. Finally,

     $myproc->kill();

   terminates the process by sending it the SIGTERM signal. As an option,
another signal can be specified.

     $myproc->kill("SIGUSR1");

   sends the SIGUSR1 signal to the running process. kill returns 1 if it
succeeds in sending the signal, 0 if it doesn't.

   The methods are discussed in more detail in the next section.

   A destructor is provided so that the forked processes can be sent a
signal automatically should the perl object be destroyed or if the perl
process exits. By default this behaviour is turned off (see the
kill_on_destroy and signal_on_destroy methods).

METHODS
=======

   The following methods are available:

new (Constructor)
     Create a new instance of this class by writing

          $proc = new Proc::Simple;

     or

          $proc = Proc::Simple->new();

     It takes no arguments.

start
     Launch a new process. For an external program to be started like from
     the shell, call

          $status = $proc->start("program-name");

     If, on the other hand, you want to start execution of a Perl function
     in the background, simply provide the function reference like

          $status = $proc->start(\&perl_function);

     or supply an unnamed subroutine:

          $status = $proc->start( sub { sleep(1) } );

     The start Method returns immediately after starting the specified
     process in background, i.e. non-blocking mode.  It returns 1 if the
     process has been launched sucessfully and 0 if not.

poll
     The poll method checks if the process is still running

          $running = $myproc->poll();

     and returns 1 if it is, 0 if it's not.

kill
     The kill() method:

          $myproc->kill();

     terminates the process by sending it the SIGTERM signal. As an
     option, another signal can be specified.

          $myproc->kill("SIGUSR1");

     sends the SIGUSR1 signal to the running process. kill returns 1 if it
     succeeds in sending the signal, 0 if it doesn't.

kill_on_destroy
     Set a flag to determine whether the process attached to this object
     should be killed when the object is destroyed. By default, this flag
     is set to false.  The current value is returned.

          $current = $proc->kill_on_destroy;
          $proc->kill_on_destroy(1); # Set flag to true
          $proc->kill_on_destroy(0); # Set flag to false

signal_on_destroy
     Method to set the signal that will be sent to the process when the
     object is destroyed (Assuming kill_on_destroy is true). Returns the
     current setting.

          $current = $proc->signal_on_destroy;
          $proc->signal_on_destroy("KILL");

pid
     Returns the pid of the forked process associated with this object

          $pid = $proc->pid;

DESTROY (Destructor)
     Object destructor. This method is called when the object is destroyed
     (eg with "undef" or on exiting perl). If kill_on_destroy is true the
     process associated with the object is sent the signal_on_destroy
     signal (SIGTERM if undefined).

exit_status
     Returns the exit status of the process as the $! variable indicates.
     If the process is still running, undef is returned.

debug
     Switches debug messages on and off - Proc::Simple::debug(1) switches
     them on, Proc::Simple::debug(0) keeps Proc::Simple quiet.

NOTE
====

   Please keep in mind that there is no guarantee that the SIGTERM signal
really terminates a process. Processes can have signal handlers defined
that avoid the shutdown.  If in doubt, whether a process still exists,
check it repeatedly with the poll routine after sending the signal.

Requirements
============

   I'd recommend using perl 5.6.0 although it might also run with 5.003
also - if you don't have it, this is the time to upgrade!

AUTHORS
=======

   Michael Schilli <michael@perlmeister.com>

   Tim Jenness  <t.jenness@jach.hawaii.edu>    did
kill_on_destroy/signal_on_destroy/pid

   Mark R. Southern <mark_southern@merck.com>    worked on EXIT_STATUS
tracking


