I have a seemingly simple problem. I need to execute a series of system commands (using backquotes) in parallel.
The code below has been stripped of anything meaningful besides demonstrating my problem:
#!/usr/bin/perl -w
use strict;
use threads;
use POSIX;
my @threads = ();
sub timeout {
print "TIMEOUT
";
foreach my $thread (@threads) {
$thread->kill("ALRM") if $thread->is_running();
}
}
POSIX::sigaction(SIGALRM, POSIX::SigAction->new(&timeout));
alarm(2);
sub threadsub {
sub handletimeout {
print "KILL
";
threads->exit(1);
}
POSIX::sigaction(SIGALRM, POSIX::SigAction->new(&handletimeout));
# while(1) { sleep(1); }
return `sleep 10`;
}
for(my $i=0; $i < 10; $i++) {
push(@threads, thread->create(&threadsub));
}
foreach my $thread (@threads) {
my $res = $thread->join();
}
Now, the problem is the ALRM signal sent to the threads are never caught when the thread is blocked in the system call. If you uncomment the while loop the signal are caught as intended. How do I make this work so I m able to timeout my threads even if they re stuck in the system command?
感谢
Kasper