Why this simple script:
#! perl -w
use strict;
use warnings;
$| = 1;
my $LOCKFILE = "$0.lock";
sub mklock {
open my $lf, ">", $LOCKFILE;
print $lf $$;
close $lf;
}
sub rmlock { unlink $LOCKFILE; }
sub clean_exit { rmlock; exit 0; }
sub work {
print "working...";
sleep 10;
# although `sleep 1 foreach (1..10);`
# *does* interrupt---between `sleep`s--see my answer
print "done.\n"
}
$SIG{INT} = "clean_exit";
mklock;
work;
rmlock;
works on Debian but not on Windows?
- on Windows, the Ctrl+C is ignored when this script is working
- on Debian, clean exit is performed as expected
- with
$SIG{INT} = \&clean_exit;, the behavior seems the same - (if I do the same with
SIGHUP($SIG{HUP} = "clean_exit";), window is closed but clean exit is not performed anyway)
(Well, I admit that it’s Strawberry perl 5, version 14, subversion 2 (v5.14.2) built for MSWin32-x86-multi-thread on Windows 7 amd64 -vs- perl, v5.10.1 (*) built for x86_64-linux-gnu-thread-multi on the Debian 6.0.4 box, but I doubt it matters for such basic stuff. Edit: I just checked it on similar box with ActiveState perl 5.12 and it’s the same, so apparently the problem is not isolated to Strawberry.)
I know perlport says it clear,
Don’t count on signals or %SIG for anything.
but there must be a way… (Plus, I would like to understand.)
So what should be done differently?
After adding some more
printing, I found out that actually, the code does work, except that it does not interrupt duringsleep.So just changing
sleep 60to more “realistic”sleep 1 foreach (1..10);brings much more acceptable behavior.It still does work differently on Windows than on *nix, of course.