http://qs321.pair.com?node_id=375307


in reply to Re^2: Creating a perl daemon
in thread Creating a perl daemon

Ok, your program also runs in a terminal and you don't want to lose that capacity. We'll define a boolean command line option, -d, which means "run as daemon". This is a modification to your existing program. It is also possible to exec another program after daemon_init is called, so a daemonizing wrapper is just as easy.

#!/usr/bin/perl use warnings; use strict; use Getopt::Std; our $opt_d, %config; getopt('d');
Now, $opt_d will be true if the -d option appears in the command line. If it does we want to set up our new SIGHUP handler, call daemon_init(), drop root priviledge, and open our new I/O streams.
use POSIX qw/setuid setsid/; if ($opt_d) { $SIG{'HUP'} = sub { %config = %{ +do '/etc/mydaemon/config' } }; daemon_init( *STDERR, *STDOUT, *STDIN); setuid( scalar getpwnam $config{'run_as'} ) unless $<; open STDIN, '<', '/dev/null' or die $!; open STDOUT, '>', '/dev/null' or die $!; open STDERR, '>>', '/var/log/mydaemon.log'; } # Be sure to define sub daemon_init # On with the program . . .
You'll need to look closely at your requirements to see if this does what you want. I made all kinds of simplifying assumptions in writing that. For instance, if you already have option option handling, you should modify this to fit what you already have.

This is just an outline, there are lots of choices and this is not cast in stone. You'll need to pay close attention to the suid part. It is there to drop privilege when the daemon is run by root. You'll need to make sure the real log path is writable by the daemon user.

This setup is nearly the same if you use Proc::Daemon. Tho only difference is that the call to &Proc::Daemon::Init takes no arguments.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^4: Creating a perl daemon
by suyashjain (Initiate) on May 20, 2013 at 13:10 UTC
    This always works for me.
    daemonize(); sub daemonize { chdir '/' or die "Can't chdir to /: $!"; open STDIN, '/dev/null' or die "Can't read /dev/null: $!"; open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!"; defined(my $pid = fork) or die "Can't fork: $!"; exit if $pid; setsid or die "Can't start a new session: $!"; open STDERR, '>&STDOUT' or die "Can't dup stdout: $!"; }
    I found it by googling.
    Suyash Jain suyash@linuxhacks.in http://www.LinuxHacks.in A Blog for Every Windows User,FEEL THE Linux freedom To RULE THE BOX.