Lp 1933984: Improve OpenSRF::Utils::daemonize
authorJason Stephenson <jason@sigio.com>
Thu, 1 Jul 2021 18:28:36 +0000 (14:28 -0400)
committerJason Stephenson <jason@sigio.com>
Sat, 3 Jul 2021 22:45:10 +0000 (18:45 -0400)
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>
src/perl/lib/OpenSRF/Utils.pm

index bb6858a..d43a41f 100644 (file)
@@ -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 $$;
        }
 }