Search code examples
c++windowscmddos

Run .exe with limited life span?


I was wondering if it was possible to run a program via cmd, except with the restriction that the program has only 5 seconds to complete its task.

The reason is because the program I am calling can either complete very quickly (<1 second) or go into an infinite loop. In the case of infinite loop, I do not want the rest of my script to hang.

For example,

cd "c:/temp"
countfiles.exe -loopIfMoreThan2Files
echo "Done"         # <--- will never be reached if there are more than 2 files

Solution

  • The following code should do it as long as no other programs with the same filename need to be running, but it would really be better to fix the exe you're calling.

    cd "c:/temp"
    start "" "countfiles.exe"
    ping -n 5 localhost
    taskkill /f /im countfiles.exe
    echo "Done"
    

    Edit: corrected /img to /im