Rishabh Gupta
Rishabh Gupta

Reputation: 21

How to set timeout for a command in cmd

I want to run a command, and if it does not complete in 1 sec I want it to return 31744.

Example:

C:\Users\Admin\Desktop\my_django_stuff>mycommand < input.txt > output txt 
timeout /t 1

This gives me a syntax error, and if the running time of my command is infinite, then it is also not stopping after 1 sec.

Upvotes: 2

Views: 20435

Answers (2)

double-beep
double-beep

Reputation: 5504

Here is a possible solution:

@echo off

start "custom" mycommand < input.txt > output txt 
timeout /t 1
taskkill /FI "WINDOWTITLE eq custom" /FI "IMAGENAME eq mycommand" /f | findstr /c:"PID" >nul
if errorlevel 1 (
    echo Task was killed!
    pause>nul
    exit /b 0
) else (
    echo The task was killed successfully! Will exit with code your_custom_code
    pause>nul
    exit /b your_custom_code
)

Now, you are sure that the program has been terminated (forcibly).

Please note that here we use timeout instead of ping as it will surely last something less than 1/4 seconds. So, as taskkill will last a bit, you will have surely something more than 1 second.

Upvotes: 2

Stephan
Stephan

Reputation: 56180

start "UniqueWindowTitle" mycommand < input.txt > output txt
ping -n 2 localhost >nul
taskkill /FI "WINDOWTITLE eq UniqueWindowTitle" /f |find " PID " && (
   echo task was killed.
   exit /b 31744
) || (
   echo there was no task to kill.
   echo it terminated in time.
)

Sadly taskkill does not return a useful errorlevel, so we parse the output (if the task was killed, it's SUCCESS: Sent termination signal to the process with PID 12345.
Dependent on your actual application you might or might not need the /f parameter ("Force")

I replaced timeout with ping-n 2 localhost, because timeout 1 does actually not wait 1 second, but until "next second" arrives - which could be only some milliseconds in extreme situations.

Also, I didn't look for "SUCCESS" but for " PID " to keep it language independent. (there is no PID, when the process was no found).

Upvotes: 3

Related Questions