"OPTION 2" doesn't timeout at all, it waits for external command to complete normally. I think because you used backticks instead of system, Perl didn't die in 3 sec but waited until STDOUT of spawned process was closed. This should work:
use strict;
use warnings;
my $timeout_msg = "Timeout after 3 seconds!\n";
my $t = time;
my $pid;
eval {
local $SIG{ ALRM } = sub { die $timeout_msg };
alarm 3;
$pid = system 1, 'timeout /t 6 > nul && echo Good Morning!';
waitpid $pid, 0;
alarm 0
};
if ( $@ ) {
die $@ unless $@ eq $timeout_msg;
print $@;
kill 'KILL', $pid
}
print time - $t, "\n";
I hope my use of timeout command won't confuse you to insert it somewhere in your code:), it's just to emulate long-running process. More important is Perl Windows system extension.