From 6fe9f449aab9a28b2e6ef65186c7b23247e0f871 Mon Sep 17 00:00:00 2001 From: Jason Stephenson Date: Thu, 1 Jul 2021 14:28:36 -0400 Subject: [PATCH] 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 --- src/perl/lib/OpenSRF/Utils.pm | 13 +++++++++++++ 1 file changed, 13 insertions(+) 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 $$; } } -- 2.11.0