2

I'm using PSEXEC to run remote process with system($CMD) in perl.

I have a computer (lets call it-#1) that runs system cmd, and another computer (lets call it-#2), which "receives" commands from computer #1.

Sometimes the process in the second computer (#2) gets stuck.

How can I set a timeout to the system cmd in computer #1 that will force-terminate the cmd after several minutes?


thanks for the answers, but: i'm tring to do somthing very simple, I have 2 perl files. file#1 that counting seconds 1 to 10. (+print to the screen) file#2-Timeout file that cal file#1 (system command) that should terminate file #1 after 5 sec.

the results...: timeout occurred, but process #1 still running...

file#2

$timeout=5;
eval {
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
    alarm $timeout;
    $nread = system('F:\perl1.pl');
    alarm 0;
};
if ($@) {
    die unless $@ eq "alarm\n";   # propagate unexpected errors
    print "process terminated\n";}
else {
    # didn't
}

file#1

$i=0;
while($

    i<10){
    sleep(1);
    $i++;

print "$i\n";
}

CMD window results:

C:\>F:\perl2.pl
1
2
3
4
process terminated

C:\>5
6
7
8
9
10
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
user2451547
  • 41
  • 1
  • 5
  • 2
    [`perldoc -q timeout`](http://perldoc.perl.org/perlfaq8.html#How-do-I-timeout-a-slow-event%3f) – daxim Jun 04 '13 at 12:56

2 Answers2

4

Let IPC::Run handle that for you.

use IPC::Run qw( run timeout );

run \@cmd, timeout( 120 )
   or die "cat: $?";
ikegami
  • 367,544
  • 15
  • 269
  • 518
2

You could use alarm in your situation:

If you want to use alarm to time out a system call you need to use an eval/die pair. You can't rely on the alarm causing the system call to fail with $! set to EINTR because Perl sets up signal handlers to restart system calls on some systems. Using eval/die always works, modulo the caveats given in Signals in perlipc.

eval {
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
    alarm $timeout;
    $nread = sysread SOCKET, $buffer, $size;
    alarm 0;
};
if ($@) {
    die unless $@ eq "alarm\n";   # propagate unexpected errors
    # timed out
}
else {
    # didn't
}
Zaid
  • 36,680
  • 16
  • 86
  • 155