develooper Front page | perl.perl5.porters | Postings from May 2002

[PATCH pod/perlipc.pod] Handling the SIGHUP Signal in Daemons

Thread Next
Stas Bekman
May 30, 2002 00:29
[PATCH pod/perlipc.pod] Handling the SIGHUP Signal in Daemons
Message ID:
inlined and attached in case the patch gets mangled

--- pod/perlipc.pod.orig	2002-05-30 14:55:24.000000000 +0800
+++ pod/perlipc.pod	2002-05-30 15:26:22.000000000 +0800
@@ -168,6 +168,66 @@
  the F<t/lib/posix.t> file from the Perl source distribution has some
  examples in it.

+=head2 Handling the SIGHUP Signal in Daemons
+A process that usually starts when the system boots and shuts down
+when the system shuts down is called a daemon (Disk And Execution
+MONitor). If a daemon process has a configuration file which is
+modified after the process has been started, there should be a way to
+tell that process to re-read its configuration file, without stopping
+the process. Many daemons provide this mechanism using the C<SIGHUP>
+signal handler. When you want to tell the daemon to re-read the file
+you simply send it the C<SIGHUP> signal.
+The implementation of such a mechanism in Perl using a normal signal
+handler works only the first time the signal is sent. The solution to
+this problem is to use the C<POSIX> signal handlers if available.
+The following example implements a simple daemon, which restarts
+itself every time the C<SIGHUP> signal is received. The actual code is
+located in the subroutine C<code()>, which simply prints some debug
+info to show that it works and should be replaced with the real code.
+  #!/usr/bin/perl -w
+  use POSIX ();
+  use FindBin ();
+  use File::Basename ();
+  use File::Spec::Functions;
+  $|=1;
+  # make the daemon cross-platform, so exec always calls the script
+  # itself with the right path, no matter how the script was invoked.
+  my $script = File::Basename::basename($0);
+  my $SELF = catfile $FindBin::Bin, $script;
+  # POSIX unmasks the sigprocmask properly
+  my $sigset = POSIX::SigSet->new();
+  my $action = POSIX::SigAction->new('sigHUP_handler',
+                                     $sigset,
+                                     &POSIX::SA_NODEFER);
+  POSIX::sigaction(&POSIX::SIGHUP, $action);
+  sub sigHUP_handler {
+      print "got SIGHUP\n";
+      exec($SELF, @ARGV) or die "Couldn't restart: $!\n";
+  }
+  code();
+  sub code {
+      print "PID: $$\n";
+      print "ARGV: @ARGV\n";
+      my $c = 0;
+      while (++$c) {
+          sleep 2;
+          print "$c\n";
+      }
+  }
+  __END__
  =head1 Named Pipes

  A named pipe (often referred to as a FIFO) is an old Unix IPC

Stas Bekman            JAm_pH ------> Just Another mod_perl Hacker     mod_perl Guide --->

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About