Problems with $SIG{WINCH} when using it in a modul

2019-06-02 04:28发布

问题:

When I use this module in a script, the if ( $size_changed ) { remains false when I've changed the terminal size.
When I copy the code from the module directly in a script (so that I don't have to load the module) it works as expected.
What could it be that loading the code as a module doesn't work?

use warnings;
use 5.014;
package My_Package;
use Exporter 'import';
our @EXPORT = qw(choose);

my $size_changed;
$SIG{WINCH} = sub { $size_changed = 1; };

sub choose {
    # ...
    # ...
    while ( 1 ) {
        my $c = getch();
        if ( $size_changed ) {
            write_screen();
            $size_changed = 0;
            next;
        }
        # ...
        # ...
    }
}

回答1:

I think I've found the reason: apart from this module I load a second module which does use $SIG{WINCH} too.
When I don't load the second module the choose subroutine works as expected.



回答2:

Why are you modifying a variable then waiting for it in an infinite loop?

Wouldn't be better if you call that sub from signal handler directly?

$SIG{WINCH} = sub { print STDERR "WINCH!\n";choose(); };

This handler is in your module main secion, it is executed in complie time not execution time and only if you using use not require.

Maybe this is works in a module

local $size_changed;
BEGIN{
   $SIG{WINCH} = sub { $size_changed = 1; };
}

Just a guess: try to use Perl::Unsafe::Signals.

use Perl::Unsafe::Signals;