in reply to Practical Proc::Daemon example

simple additions

I added these to the example:

GetOptions( 'daemon!' => \$daemonize, "help" => \&usage, "reload" => \&reload, "restart" => \&restart, "start" => \&run, "status" => \&status, "stop" => \&stop ) or &usage; exit(0); # ================================================== sub usage { my ($opt_name, $opt_value) = @_; print "your usage text goes here...\n"; exit(0); } # ================================================== sub reload { my ($opt_name, $opt_value) = @_; print "reload process not implemented.\n"; } # ================================================== sub restart { my ($opt_name, $opt_value) = @_; &stop; &run; } # ==================================================

Yes, they are obvious, but since that is about all I did to the example to make it a "complete" test for my system, I figured that I'd toss it back a'cha.

THANKS!!!

Lee Crites
lee@critesclan.com

Replies are listed 'Best First'.
Re^2: Practical Proc::Daemon example
by Arunbear (Prior) on Dec 05, 2014 at 17:43 UTC
    It seems as though Proc::Daemon makes you do a lot of extra work. What if you didn't have to re-invent so many wheels? Here's another way:
    #!/usr/bin/env perl # weather_watch.pl use strict; use Getopt::Long; use JSON::XS; use LWP::Simple; use Sys::Syslog; my $app = bless { city => 'London,uk', }; GetOptions( $app, 'city=s', ); $app->init; $app->run; sub init { my ($app) = @_; openlog($0, 'pid', 'user'); syslog("info", "Starting up"); $SIG{TERM} = sub { $app->{should_stop} = 1; }; } sub run { my ($app) = @_; my $url = "http://api.openweathermap.org/data/2.5/weather?q=$app-> +{city}"; until ( $app->{should_stop} ) { if ( my $json = get($url) ) { my $data = decode_json($json); syslog("info", "Temperature is $data->{main}{temp}"); syslog("info", "Wind speed is $data->{wind}{speed}"); } sleep 5; } syslog("info", "Shutting down"); closelog(); }
    The example program is not cluttered with daemonization logic and to run that in non daemon mode, just run it. To add daemonization, create a little script (all off this could be done in one script but for clarity I prefer to keep them separate):
    #!/usr/bin/perl # weathermon use warnings; use strict; use Daemon::Control; use Getopt::Long; GetOptions( \ my %OPT, 'city=s', ); exit Daemon::Control->new( name => "Weather watch daemon", path => '/home/arun/test/weathermon', program => '/home/arun/test/weather_watch.pl', program_args => [ '--city', $OPT{city} ], pid_file => '/tmp/weathermon.pid', )->run;
    Now we get all this for free:
    % ./weathermon status Weather watch daemon [Not Running +] % ./weathermon start Weather watch daemon [Started +] % ./weathermon status Weather watch daemon [Running +] % ./weathermon stop Weather watch daemon [Stopped +] % ./weathermon start -c Miami,us Weather watch daemon [Started +] % ./weathermon restart Weather watch daemon [Stopped +] Weather watch daemon [Started +] %