Improve the Perl daemonize function to:
1. Set the umask to a reasonable, known value (022).
2. Close all open file descriptors inherited from the parent.
3. Open /dev/null for standard input, standard output, and standard
error so that library calls do not clutter the console.
For the logic behind these changes see Chapter 13 of __Advanced
Programming In the UNIX Environment, 3rd Edition__ by W. Richard
Stevens and Stephen A. Rago.
Signed-off-by: Jason Stephenson <jason@sigio.com>
use DateTime;
use DateTime::Format::ISO8601;
use DateTime::TimeZone;
+use BSD::Resource;
=head1 NAME
exit 0;
} elsif (defined($pid)) {
set_psname($PS_NAME);
+ umask(022); # Something reasonable.
chdir '/';
setsid;
+ my $rlimit = getrlimit(RLIMIT_NOFILE);
+ $rlimit = ($rlimit == RLIM_INFINITY) ? 1024 : $rlimit;
+ for (my $i = 0; $i < $rlimit; $i++) {
+ POSIX::close($i);
+ }
+ # Direct STDIN, STDOUT, and STDERR to /dev/null to avoid
+ # console pollution
+ my ($fd0, $fd1, $fd2);
+ $fd0 = POSIX::open("/dev/null", O_RDWR);
+ $fd1 = dup($fd0);
+ $fd2 = dup($fd0);
return $$;
}
}