NAME
Net::Daemon - Perl extension for portable daemons
SYNOPSIS
# Create a subclass of Net::Daemon
require Net::Daemon;
package MyDaemon;
@MyDaemon::ISA = qw(Net::Daemon);
sub Run ($) {
# This function does the real work; it is invoked whenever a
# new connection is made.
}
DESCRIPTION
Net::Daemon is an approach for writing daemons that are both portable and simple. It is based on the Thread package of Perl 5.005.
The Net::Daemon class is an abstract class that offers methods for the most common tasks a daemon needs: Starting up, logging, accepting clients, authorization and doing the true work. You only have to override those methods that aren't appropriate for you, but typically inheriting will safe you a lot of work anyways.
Constructors
$server = Net::Daemon->new($attr, $options);
$connection = $server->Clone($socket);
Two constructors are available: The new
method is called upon startup and creates an object that will basically act as an anchor over the complete program. It supports command line parsing via Getopt::Long (3).
Arguments of new
are $attr, an hash ref of attributes (see below) and $options an array ref of options, typically command line arguments (for example \@ARGV
) that will be passed to Getopt::Long::GetOptions
.
The second constructor is Clone
: It is called whenever a client connects. It receives the main server object as input and returns a new object. This new object will be passed to the methods that finally do the true work of communicating with the client. Communication occurs over the socket $socket
, Clone
's argument.
Possible object attributes and the corresponding command line arguments are:
- debug (
--debug
) -
Used for turning debuging mode on.
- facility (
--facility
) -
Facility to use for Sys::Syslog (3) (Unix only). The default is
daemon
. - forking
-
Creates a forking daemon instead of using the Thread library (Unix only). There are two good reasons for using fork(): You have no multithreaded Perl or you need to simplify porting existing applications.
- localaddr (
--localaddr
) -
By default a daemon is listening to any IP number that a machine has. This attribute allows to restrict the server to the given IP number.
- localport (
--localport
) -
This attribute sets the port on which the daemon is listening.
- options
-
Array ref of Command line options that have been passed to the server object via the
new
method. - parent
-
When creating an object with
Clone
the original object becomes the parent of the new object. Objects created withnew
usually don't have a parent, thus this attribute is not set. - pidfile (
--pidfile
) -
If your daemon creates a PID file, you should use this location.
- socket
-
The socket that is connected to the client; passed as
$client
argument to theClone
method. If the server object was created withnew
, this attribute can be undef, as long as theBind
method isn't called. Sockets are assumed to be IO::Socket objects. - stderr (
--stderr
) -
By default Logging is done via Sys::Syslog (3) (Unix) or Win32::EventLog (Windows NT). This attribute allows logging to be redirected to STDERR instead.
- version (
--version
) -
Supresses startup of the server; instead the version string will be printed and the program exits immediately.
Note that most of these attributes (facility, forking, localaddr, localport, pidfile, version) are meaningfull only at startup. If you set them later, they will be simply ignored. As almost all attributes have appropriate defaults, you will typically use the localport
attribute only.
Command Line Parsing
my($optionsAvailable) = Net::Daemon->Options();
print Net::Daemon->Version(), "\n";
Net::Daemon->Usage();
The Options
method returns a hash ref of possible command line options. The keys are option names, the values are again hash refs with the following keys:
- template
-
An option template that can be passed to
Getopt::Long::GetOptions
. - description
-
A description of this option, as used in
Usage
The Usage
method prints a list of all possible options and returns. It uses the Version
method for printing program name and version.
Event logging
$server->Log($level, $format, @args);
The Log
method is an interface to Sys::Syslog (3) or Win32::EventLog (3). It's arguments are $level, a syslog level like debug
, notice
or err
, a format string in the style of printf and the format strings arguments.
Flow of control
$server->Bind();
# The following inside Bind():
if ($connection->Accept()) {
$connection->Run();
} else {
$connection->Log('err', 'Connection refused');
}
The Bind
method is called by the application when the server should start. Typically this can be done right after creating the server object $server
. Bind
usually never returns, except in case of errors.
When a client connects, the server uses Clone
to derive a connection object $connection
from the server object. A new thread or process is created that uses the connection object to call your classes Accept
method. This method is intended for host authorization and should return either FALSE (refuse the client) or TRUE (accept the client).
If the client is accepted, the Run
method is called which does the true work. The connection is closed when Run
returns and the corresponding thread or process exits.
EXAMPLE
As an example we'll write a simple calculator server. After connecting to this server you may type expressions, one per line. The server evaluates the expressions and prints the result. (Note this is an example, in real life we'd never implement sucj a security hole. :-)
For the purpose of example we add a command line option --base that takes 'hex', 'oct' or 'dec' as values: The servers output will use the given base.
# -*- perl -*-
#
# Calculator server
#
require 5.004;
use strict;
require Net::Daemon;
package Calculator;
use vars qw($VERSION @ISA);
$VERSION = '0.01';
@ISA = qw(Net::Daemon); # to inherit from Net::Daemon
sub Version ($) { 'Calculator Example Server, 0.01'; }
# Add a command line option "--base"
sub Options ($) {
my($self) = @_;
my($options) = $self->SUPER::Options();
$options->{'base'} = { 'template' => 'base=s',
'description' => '--base '
. 'dec (default), hex or oct'
};
$options;
}
# Treat command line option in the constructor
sub new ($$;$) {
my($class, $attr, $args) = @_;
my($self) = $class->SUPER::new($class, $attr, $args);
if ($self->{'parent'}) {
# Called via Clone()
$self->{'base'} = $self->{'parent'}->{'base'};
} else {
# Initial call
if ($self->{'options'} && $self->{'options'}->{'base'}) {
$self->{'base'} = $self->{'options'}->{'base'}
}
}
if (!$self->{'base'}) {
$self->{'base'} = 'dec';
}
}
sub Run ($) {
my($self) = @_;
my($line, $sock);
$sock = $self->{'socket'};
while (1) {
if (!defined($line = $sock->getline())) {
if ($sock->error()) {
$self->Log('err', "Client connection error %s",
$sock->error());
}
$sock->close();
return;
}
my($result) = eval $line;
my($rc);
if ($self->{'base'} eq 'hex') {
$rc = printf $sock ("%x\n", $result);
} elsif ($self->{'base'} eq 'oct') {
$rc = printf $sock ("%o\n", $result);
} else {
$rc = printf $sock ("%d\n", $result);
}
if (!$rc) {
$self->Log('err', "Client connection error %s",
$sock->error());
$sock->close();
return;
}
}
}
AUTHOR AND COPYRIGHT
Net::Daemon is Copyright (C) 1998, Jochen Wiedmann
Am Eisteich 9
72555 Metzingen
Germany
Phone: +49 7123 14887
Email: joe@ispsoft.de
This module is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this module; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
SEE ALSO
RPC::pServer (3)