http://www.perlmonks.org?node_id=1073446

I had a lot of trouble getting started with Proc::Daemon because some things weren't completely obvious to me. Here's a practical example that I wrote for practice.

use strict; use warnings; use Getopt::Long; use Proc::Daemon; use Cwd; use File::Spec::Functions; my $pf = catfile(getcwd(), 'pidfile.pid'); my $daemon = Proc::Daemon->new( pid_file => $pf, work_dir => getcwd() ); # are you running? Returns 0 if not. my $pid = $daemon->Status($pf); my $daemonize = 1; GetOptions( 'daemon!' => \$daemonize, "start" => \&run, "status" => \&status, "stop" => \&stop ); sub stop { if ($pid) { print "Stopping pid $pid...\n"; if ($daemon->Kill_Daemon($pf)) { print "Successfully stopped.\n"; } else { print "Could not find $pid. Was it running?\n"; } } else { print "Not running, nothing to stop.\n"; } } sub status { if ($pid) { print "Running with pid $pid.\n"; } else { print "Not running.\n"; } } sub run { if (!$pid) { print "Starting...\n"; if ($daemonize) { # when Init happens, everything under it runs in the child + process. # this is important when dealing with file handles, due to + the fact # Proc::Daemon shuts down all open file handles when Init +happens. # Keep this in mind when laying out your program, particul +arly if # you use filehandles. $daemon->Init; } while (1) { open(my $FH, '>>', catfile(getcwd(), "log.txt")); # any code you want your daemon to run here. # this example writes to a filehandle every 5 +seconds. print $FH "Logging at " . time() . "\n"; close $FH; sleep 5; } } else { print "Already Running with pid $pid\n"; } }

start, stop, and status behave as one would expect. nodaemon runs the daemon in the foreground for troubleshooting. nodaemon must be given before start or it gets ignored.

A little work will need to be done to make it init friendly. This is left as an exercise for the reader.

I'm sure there's better ways to handle the filehandle.

Suggestions are welcome and will be incorporated.

Edit: added catch in stop to not try and stop a daemon that's not running.

Edit: added clarity for what code is actually run when the daemon is running.