Auto-restart an executable after the application crashes

9,552

One solution is to use a batch file with an infinite for loop to automatically restart the application if it closes. There are two possibilities here, depending on how the application is designed.

If the application is launched and runs in the same process, you can use a very simple batch file:

@echo off
:Start
C:\path\to\application.exe
:: Wait 30 seconds before restarting.
TIMEOUT /T 30
GOTO:Start

This will run infinitely. Any time application.exe is closed or crashes, the batch file will restart it.

This will not work if application.exe launches subapp.exe and then application.exe closes. In this case, you would need something more complicated.

@ECHO off
SET _PollingInterval=30

:BatchStart
C:\path\to\application.exe

:Start
:: Uncomment the following line on versions of Windows prior to Windows 7 and comment out the TIMEOUT line. The PING solution will not be 100% accurate with _PolingInterval.
:: PING 127.0.0.1 -n %_PollingInterval% >nul
TIMEOUT /T %_PollingInterval%

SET PID=
FOR /F "tokens=2 delims= " %%i IN ('TASKLIST ^| FIND /i "subapp.exe"') DO SET PID=%%i
IF [%PID%]==[] (
    ECHO Application was not running. Restarting script.
    GOTO BatchStart
)
GOTO Start

GOTO:EOF

If your application could have various processes, then you can probably use something like FINDSTR /i "subapp.exe application.exe" instead of FIND /i "subapp.exe", but this wouldn't work for processes with spaces in their name as FINDSTR uses the space as a deliminator.

In order to stop these batch files once they've been started, leave the application open and switch to the command prompt. Then use Ctrl + C and acknowledge you want to end the script. Once the script is terminated, close the application.

Further reading:

Share:
9,552

Related videos on Youtube

Bachalo
Author by

Bachalo

Updated on September 18, 2022

Comments

  • Bachalo
    Bachalo almost 2 years

    I'm creating a standalone application for a kiosk that must be up and running 24 7.

    In the rare event the application crashes, I need some way to make it auto-restart. I'm running Windows 10 on a Nuc.

    Can any Windows experts suggest the best way to achieve this?

    • LPChip
      LPChip almost 6 years
      Another option could be to create a service of the application. A service can be set to restart itself 3 times. This will eliminate a command prompt window being shown that can be closed by anyone. This is harder to setup though...
  • Bachalo
    Bachalo almost 6 years
    Thanks! One quick question, how would I add a delay to the simplest (1st) solution so the application wouldn't restart immediately?
  • Worthwelle
    Worthwelle almost 6 years
    You can use the TIMEOUT command. I've added it to the example in the answer.