S
Stefan Weiss
Hi.
I have a daemon class that needs to handle signals like USR1, USR2, INT,
and TERM depending on the internal state. The way I do it at the moment
is visible in the short demo script below. It works, but I have to admit
that I'm not exactly sure _why_ it works.
Can somebody please explain what happens with that anonymous sub that
gets assigned to $SIG{INT} and $SIG{TERM} in line 22? Where does it take
the value of "$self" from? If it's from the surrounding scope, then how
can it know (later on) that the "running" attribute has changed from 0
to 1? Is this the proper way to do signal handling in an OO context?
TIA,
stefan
------------------------------------------------------------------------
#!/usr/bin/perl
use strict;
use warnings;
my $Daemon = new MyModule;
$Daemon->mainLoop;
package MyModule;
use strict;
use warnings;
sub new {
my $class = shift;
my $obj = {
name => "MyName",
running => 0,
};
my $self = bless $obj, $class;
$SIG{TERM} = $SIG{INT} = sub { $self->handleSignal(shift) };
return $self;
}
sub handleSignal {
my ($self, $sig) = @_;
$self->qlog("info", "caught signal $sig; running: $self->{running}");
$self->qlog("notice", "$self->{name} controlled shutdown");
exit 0;
}
sub qlog {
my ($self, $lvl, $msg) = @_;
print "[$lvl] $msg\n";
}
sub mainLoop {
my $Xself = shift;
$Xself->{running} = 1;
print "in main loop\n";
for (; { sleep 1 }
}
I have a daemon class that needs to handle signals like USR1, USR2, INT,
and TERM depending on the internal state. The way I do it at the moment
is visible in the short demo script below. It works, but I have to admit
that I'm not exactly sure _why_ it works.
Can somebody please explain what happens with that anonymous sub that
gets assigned to $SIG{INT} and $SIG{TERM} in line 22? Where does it take
the value of "$self" from? If it's from the surrounding scope, then how
can it know (later on) that the "running" attribute has changed from 0
to 1? Is this the proper way to do signal handling in an OO context?
TIA,
stefan
------------------------------------------------------------------------
#!/usr/bin/perl
use strict;
use warnings;
my $Daemon = new MyModule;
$Daemon->mainLoop;
package MyModule;
use strict;
use warnings;
sub new {
my $class = shift;
my $obj = {
name => "MyName",
running => 0,
};
my $self = bless $obj, $class;
$SIG{TERM} = $SIG{INT} = sub { $self->handleSignal(shift) };
return $self;
}
sub handleSignal {
my ($self, $sig) = @_;
$self->qlog("info", "caught signal $sig; running: $self->{running}");
$self->qlog("notice", "$self->{name} controlled shutdown");
exit 0;
}
sub qlog {
my ($self, $lvl, $msg) = @_;
print "[$lvl] $msg\n";
}
sub mainLoop {
my $Xself = shift;
$Xself->{running} = 1;
print "in main loop\n";
for (; { sleep 1 }
}