Skip to content

Instantly share code, notes, and snippets.

@stepnem
Created April 11, 2024 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stepnem/738d7d2e21bc4ab3d1d0a715c4a8bf86 to your computer and use it in GitHub Desktop.
Save stepnem/738d7d2e21bc4ab3d1d0a715c4a8bf86 to your computer and use it in GitHub Desktop.
perlipc.pod signal handler exec example
#!/bin/sh
check() {
printf '\nTesting %s\n' "$*"
"$@" &
sleep 1
kill -HUP $!
sleep 1
kill -HUP $!
sleep 1
kill $!
}
bad=./perlipc-sighandler-bad.perl
good=./perlipc-sighandler-good.perl
# from current perlipc.pod (perl5 commit e78caca8144e v5.39.9-35-ge78caca8144e)
cat <<\EOF >"$bad"
#!/usr/bin/perl
use v5.36;
use POSIX ();
use FindBin ();
use File::Basename ();
use File::Spec::Functions qw(catfile);
$| = 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
$SIG{HUP} = sub {
print "got SIGHUP\n";
exec( $SELF, @ARGV ) || die "$0: couldn't restart: $!";
};
code();
sub code {
print "PID: $$\n";
print "ARGV: @ARGV\n";
my $count = 0;
while (1) {
sleep 2;
print ++$count, "\n";
}
}
EOF
# from perlipc.pod before perl5 commit de7ba5179657 v5.15.2-343-gde7ba5179657
cat <<\EOF >"$good"
#!/usr/bin/perl
use v5.36;
use POSIX ();
use FindBin ();
use File::Basename ();
use File::Spec::Functions qw(catfile);
$| = 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 ) || die "$0: couldn't restart: $!";
}
code();
sub code {
print "PID: $$\n";
print "ARGV: @ARGV\n";
my $count = 0;
while (1) {
sleep 2;
print ++$count, "\n";
}
}
EOF
chmod +x "$bad" "$good"
check "$bad"
check "$good"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment