Search code examples
windowsbatch-filecmd

Close 2 programs, one after another, with a batch file


I have 2 programs, A and B. I made a batch file to have them open simultaneously, and now I want to have them both close when I exit program A.

Here's my code so far:

@echo off

cd "C:\prog\test"
start A.exe

cd "C:\prog\test"
start B.exe

exit

I can't find any tutorial that doesn't involve some kind of timer. Problem is, I have no idea how long I'll be working with them before closing. Can anyone help?


Solution

  • Something along this line.

    @echo off
    START
    cd "C:\prog\test\"
    startA.exe && startB.exe
    
    :TEST
    tasklist /FI "IMAGENAME eq startA.exe" 2>NUL | find /I /N "startA.exe">NUL 
    if "%ERRORLEVEL%"=="0" goto ACTIVE
    
    :DEAD
    taskkill /f /im startB.exe
    exit
    
    :ACTIVE
    timeout /T 10
    goto TEST
    

    So to explain.

    You start your programs, then test for startA.exe using tasklist. If the task returns Errorlevel==0 it means it is running. We then send to the waiting section for 10 seconds, and go back to test if startA.exe is running. If however the errorlevel is not 0, it will go directly to DEAD and kill startB.exe