Daemon(3pm)
π Daemon(3pm) β App::Daemon π
okay bestie, so this is the App::Daemon page from the User Contributed Perl Documentation section of the manual, and it's literally about making your app run as a daemon. no cap. let's get into it πΈ
β¨ NAME β¨
App::Daemon β Start an Application as a Daemon π¦
β¨ SYNOPSIS β¨
first, the program side of things:
# Program:
use App::Daemon qw( daemonize );
daemonize();
do_something_useful(); # your application
then, from the shell, you start the app β and it comes right back to you, but keeps running do_something_useful() in the background:
# Then, in the shell: start application,
# which returns immediately, but continues
# to run do_something_useful() in the background
$ app start
$
stopping it:
# stop application
$ app stop
running it in the foreground (for testing, queen):
# start app in foreground (for testing)
$ app -X
and checking whether it's currently running:
# show if app is currently running
$ app status
β¨ DESCRIPTION β¨
App::Daemon helps you run an application as a daemon. the whole idea is that you prepend your script with
use App::Daemon qw( daemonize );
daemonize();
and boom, it's daemonized. so if you write
use App::Daemon qw( daemonize );
daemonize();
sleep(10);
you get a script that, when you call it from the command line, returns immediately but keeps running as a daemon for 10 seconds. iconic behaviour honestly π
on top of the usual features that the other similar modules on CPAN offer, it also:
- supports logging with Log4perl β in background mode it logs to a logfile, and in foreground mode log messages go straight to the screen π₯οΈ
- detects if another instance is already running and just ends itself automatically in that case
- shows you, with the 'status' command, whether an instance is already running and which PID it has:
./my-app status
Pid file: ./tt.pid
Pid in file: 14914
Running: no
Name match: 0
π Actions π
App::Daemon recognizes three different actions:
my-app start
- will start up the daemon. fun fact:
startitself is optional, because this is the default action, so
$ ./my-app
$
- will also run the 'start' action. by default it creates a pid file and a log file in the current directory (named
my-app.pidandmy-app.log). to change these locations, see the-land-poptions. - if the
-Xoption is given, the program runs in foreground mode for testing purposes:
$ ./my-app -X
...
stop
- will find the daemon's PID in the pidfile and send it a
SIGTERMsignal. it will verify$App::Daemon::kill_retriestimes whether the process is still alive, with 1-second sleeps in between. - to have App::Daemon send a different signal than
SIGTERM(e.g.,SIGINT), set
use POSIX;
$App::Daemon::kill_sig = SIGINT;
note that this requires the numerical value (SIGINT via POSIX.pm), not a string like "SIGINT". β οΈ
status
- will print out diagnostics on what the status of the daemon is. typically the output looks like this:
Pid file: ./tt.pid
Pid in file: 15562
Running: yes
Name match: 1
/usr/local/bin/perl -w test.pl
- this means the pidfile says the daemon has PID 15562 and that a process with this PID is actually running right now. also, a name grep on the process name in the process table gives 1 match, per the output above.
- note that the name match is unreliable, because it just looks for a command line that looks approximately like the script itself. so if the script is
test.pl, it'll match lines likeperl -w test.plorperl test.pl startβ but unfortunately also lines likevi test.pl. π - if the process is no longer running, the status output might look like this instead:
Pid file: ./tt.pid
Pid in file: 14914
Running: no
Name match: 0
- the status command's exit code complies with
http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
- and returns
0: if the process is up and running
1: the process is dead but the pid file still exists
3: the process is not running
- these constants are defined within App::Daemon to help writing test scripts:
use constant LSB_OK => 0;
use constant LSB_DEAD_PID_EXISTS => 1;
use constant LSB_DEAD_LOCK_EXISTS => 2;
use constant LSB_NOT_RUNNING => 3;
use constant LSB_UNKNOWN => 4;
use constant ALREADY_RUNNING => 150;
π Command Line Options π
-Xβ Foreground mode. Log messages go to the screen.-l logfileβ Logfile to send Log4perl messages to in background mode. Defaults to"./[appname].log". Note that having a logfile in the current directory doesn't make sense except for testing environments, make sure to set this to somewhere within"/var/log"for production use.-u as_userβ User to run as if started as root. Defaults to 'nobody'.-g as_groupβ Group to run as if started as root. Defaults to 'nogroup'.-l4p l4p.confβ Path to Log4perl configuration file. Note that in this case the-voption will be ignored.-p pidfileβ Where to save the pid of the started process. Defaults to"./[appname].pid". Note that having a pidfile in the current directory doesn't make sense except for testing environments, make sure to set this to somewhere within"/var/run"for production use.-vβ Increase default Log4perl verbosity from$INFOto$DEBUG. Note that this option will be ignored if Log4perl is initialized independently or if a user-provided Log4perl configuration file is used.
π§ Setting Parameters π§
instead of setting parameters like the logfile, the pidfile etc. from the command line, you can go straight in and manipulate App::Daemon's global variables:
use App::Daemon qw(daemonize);
$App::Daemon::logfile = "mylog.log";
$App::Daemon::pidfile = "mypid.log";
$App::Daemon::l4p_conf = "myconf.l4p";
$App::Daemon::background = 1;
$App::Daemon::as_user = "nobody";
$App::Daemon::as_group = "nogroup";
use Log::Log4perl qw(:levels);
$App::Daemon::loglevel = $DEBUG;
daemonize();
π Application-specific command line options π
if an application needs additional command line options, it can use whatever isn't already taken by App::Daemon, as described previously in the "Command Line Options" section.
however, it needs to make sure to remove these additional options before calling daemonize(), or App::Daemon will complain. to do this, create an options hash %opts and store application-specific options in there while removing them from @ARGV:
my %opts = ();
for my $opt (qw(-k -P -U)) {
my $v = App::Daemon::find_option( $opt, 1 );
$opts{ $opt } = $v if defined $v;
}
after this, options -k, -P, and -U will have disappeared from @ARGV and can be checked in $opts{k}, $opts{P}, and $opts{U}. β¨
π Gotchas π
Log File Permissions
if the process is started as root but later drops permissions to a non-privileged user for security purposes, it's important that logfiles are created with correct permissions.
if they're created as root when the program starts, the non-privileged user won't be able to write to them later (unless they're world-writable, which is also undesirable because of security concerns). π
the best strategy to handle this case is to specify the non-privileged user as the owner of the logfile in the Log4perl configuration:
log4perl.logger = DEBUG, FileApp
log4perl.appender.FileApp = Log::Log4perl::Appender::File
log4perl.appender.FileApp.filename = /var/log/foo-app.log
log4perl.appender.FileApp.owner = nobody
log4perl.appender.FileApp.layout = PatternLayout
log4perl.appender.FileApp.layout.ConversionPattern = %d %m%n
this way, the process starts up as root, creates the logfile if it doesn't exist yet, and changes its owner to 'nobody'. later, when the process assumes the identity of the user 'nobody', it will continue to write to the logfile without permission problems. slay π«Ά
Log4perl Categories
note that App::Daemon is logging messages in Log4perl's App::Daemon namespace. so if you're running your own Log4perl configuration and define a root logger like
log4perl.logger=DEBUG, appendername
then App::Daemon's messages will bubble up to it and be visible in the output. if you don't want that, either use
log4perl.logger.My.App=DEBUG, appendername
to explicitly enable verbose logging in your application namespace (and not in App::Daemon's) or tone down App::Daemon's verbosity via
log4perl.logger.App.Daemon=ERROR
explicitly. if you want more details on basic Log4perl features, check out the Log::Log4perl manual page. π
π¦ Detach only π¦
if you want to create a daemon without the fancy command line parsing and PID file checking functions, use
use App::Daemon qw(detach);
detach();
# ... some code here
this will fork a child, terminate the parent and detach the child from the terminal. issued from the command line, the program above will continue to run the code following the detach() call but return to the shell prompt immediately. main character energy fr fr π
β¨ AUTHOR β¨
2008, Mike Schilli <cpan@perlmeister.com>
β¨ LICENSE β¨
Copyright 2008-2012 by Mike Schilli, all rights reserved. This program is free software, you can redistribute it and/or modify it under the same terms as Perl itself.
okay that's the whole page bestie π this was perl v5.26.2, dated 2018-07-08, and the manual is Daemon(3pm). go daemonize something cute, you've got this πβ¨π
π¦ where this page comes from
- debian bookworm: libapp-daemon-perl 0.22-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libapp-daemon-perl 0.22-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu jammy: libapp-daemon-perl 0.22-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libapp-daemon-perl 0.22-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms