Search code examples
perldaemon

Daemonize a perl script


Currently I am looking to daemonize a perl script. Sadly most answers are out of date and I actually quite do not understand how to begin the daemon process (especially daemon perl scripts).

Right now I am looking at Proc Daemon but again I do not know where to begin or whether it should be done with or without the use of a modules.

I believe if I give an example of what I am look for to give this question a little more direction.

Example

Say I am on osx and I want to write a perl script that can run as a daemon. It responds to the signal HUP which then proceeds to print the contents from a file from a certain directory.If it recieves signal USR1 it prints out the content differently. What is the most appropriate way to do this as a daemon?


Solution

  • This is all you need:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Daemon::Daemonize qw( daemonize write_pidfile );
    
    sub sighup_handler {
       ...
    }
    
    sub sigusr1_handler {
       ...
    }
    
    {
       my $name          = "...";
       my $error_log_qfn = "/var/log/$name.log";
       my $pid_file_qfn  = "/var/run/$name.pid";
    
       daemonize(
          close  => 'std',
          stderr => $error_log_qfn,
       );
    
       $SIG{HUP}  = \&sighup_handler;
       $SIG{USR1} = \&sigusr1_handler;
    
       write_pidfile($pid_file_qfn);
    
       sleep while 1;
    }