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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|