Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Daemonize a perl script

Tags:

perl

daemon

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?

like image 379
MooCow Avatar asked Feb 10 '23 08:02

MooCow


1 Answers

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;
}
like image 63
ikegami Avatar answered Feb 27 '23 02:02

ikegami