From: Jason Stephenson Date: Thu, 1 Jul 2021 18:28:36 +0000 (-0400) Subject: Lp 1933984: Improve OpenSRF::Utils::daemonize X-Git-Url: https://old-git.evergreen-ils.org/?a=commitdiff_plain;h=6fe9f449aab9a28b2e6ef65186c7b23247e0f871;p=working%2FOpenSRF.git Lp 1933984: Improve OpenSRF::Utils::daemonize 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 --- diff --git a/src/perl/lib/OpenSRF/Utils.pm b/src/perl/lib/OpenSRF/Utils.pm index bb6858a..d43a41f 100644 --- a/src/perl/lib/OpenSRF/Utils.pm +++ b/src/perl/lib/OpenSRF/Utils.pm @@ -9,6 +9,7 @@ use Exporter; use DateTime; use DateTime::Format::ISO8601; use DateTime::TimeZone; +use BSD::Resource; =head1 NAME @@ -426,8 +427,20 @@ sub daemonize { 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 $$; } }