Danny Ho
Danny Ho

Reputation: 149

How to set timeout for a cmd command?

i just have the following command in cmd

perl csv2rrd3.pl

but it always run for a long time. Is there any way to set a timeout for it? or i should do it in the perl script?? And how?

Thanks

Upvotes: 4

Views: 3145

Answers (4)

Brian H.
Brian H.

Reputation: 2235

Updated answer if PowerShell is available:

The starting, waiting, and killing of the command all hapens within Powershell, making this work for any envrionment, not just Peral.

$x = Start-Process -Filepath "ping" -ArgumentList 'google.com -n 100' -NoNewWindow -PassThru; 
Start-Sleep -Seconds 5; 
try { Stop-Process -Id $x.Id -ErrorAction stop } catch {};

Replace ping and the argumnets list with whatver needs to run.

If you need an early return (e.g. the process will end either when the command finishes or the timeout is reached, then replace Start-Sleep ... with a loop that checks if $x.Id is still an active process, then sleeps for 1 second if it is.

Upvotes: 0

Matthias
Matthias

Reputation: 7521

From the windows command line, you can first start the perl script in its own window, chain it with the timeout command to wait x seconds (here 2) and then chain it again with the taskkill command to kill the process.

start perl csv2rrd3.pl & timeout -t 2 & taskkill /IM perl.exe

The line above would kill every perl process. To kill only your just started one, you could use a custom window title.

start "KILLME" perl csv2rrd3.pl & timeout -t 2 & taskkill /FI "WINDOWTITLE eq KILLME" /IM perl.exe

Upvotes: 6

amon
amon

Reputation: 57600

Inside of Perl, you can set an alarm to go off after a few seconds. You can then use a signal handler to catch the event. Only one alarm may be active at any time

{ # enter new scope
    # set signal handler
    local $SIG{ALRM} = sub {
       # do cleanup, like closing sockets or whatever
       print STDERR "exited with ALARM\n";
       exit;
    };
    alarm 30; # try half a minute
    ...; # do expensive stuff
}

Upvotes: 8

xhudik
xhudik

Reputation: 2444

well, not sure about timeout, but you can wait some specific time and then kill the process.

sleep(10) # sleep 10 seconds
kill      # and insert PID of the process (see command ps)

Upvotes: 0

Related Questions