And call $object->set_signal_handlers() after creating the object (or $self->set_signal_handlers() from within the object itself).sub set_signal_handlers { my $self=shift; $SIG{USR1}=sub { $self->handler_USR1() } ... } sub handler_USR1 { my $self=shift; # Now I can access the object through $self }
package Obj; # Class variable $handlers={}; sub new { my $class = shift; my $self = { @_ }; bless $self, $class; $self->set_signal_handlers; $self; } sub name { shift->{'name'}; } sub set_signal_handlers { my $self = shift; # Set handlers for USR1 if (!$handlers{USR1}) { # Class signal handler, only set the first time $SIG{USR1} = sub { class_handle_signal('USR1'); }; } # You could index by $self->name, or by any other identifier $handlers->{USR1}->{$self} = $self->handle_USR1(); # Set handlers for USR1 if (!$handlers{USR2}) { $SIG{USR2} = sub { class_handle_signal('USR2'); } } $handlers->{USR2}->{$self} = $self->handle_USR2(); } sub handle_USR1 { my $self = shift; return sub { print "handling USR1 for ", $self->name, "\n"; } } sub handle_USR2 { my $self = shift; return sub { print "handling USR2 for ", $self->name, "\n"; } } sub class_handle_signal { my $sig=shift; foreach (keys %{$handlers->{$sig}}) { &{$handlers->{$sig}->{$_}}(); } } package main; my $obj1 = new Obj(name => 'obj1'); my $obj2 = new Obj(name => 'obj2'); while (1) { }
|
---|
Replies are listed 'Best First'. | |
---|---|
RE: Setting up signal handlers for an object with access to $self
by chromatic (Archbishop) on Apr 19, 2000 at 23:02 UTC | |
by ZZamboni (Curate) on Apr 19, 2000 at 23:03 UTC | |
by chromatic (Archbishop) on Apr 19, 2000 at 23:19 UTC | |
RE: Setting up signal handlers for an object with access to $self
by btrott (Parson) on Apr 20, 2000 at 00:26 UTC | |
by ZZamboni (Curate) on Apr 20, 2000 at 01:39 UTC | |
by chromatic (Archbishop) on Apr 20, 2000 at 02:41 UTC |