Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to detect if a batch file is already running or not.

In the batch I simply loop and repeatedly do some tasks. Sometimes the loop cannot complete. I run the batch file at a scheduled time. When it runs, it should check if a previous instance exists and is healthy. If it doesn't exist it should start a new instance. If the instance that exist is not healthy/outdated, the new instance should kill/cancel the older process.

A few theories:

  1. How can I detect a previous instance in a batch file? Can I give an ID like thing?
  2. I can use a pulse mechanism to say the batch is healty; ie, a global variable, a newly created dummy file, a timestamp in a dummy file, etc.
  3. Can I detect a kind of "timeout", if the last pulse is expired then allow a new instance...

Yes, I all want them in a batch file - instead of a Windows app - I think it's not so hard for one who is a batch-file addict and takes this question as challenge!

share|improve this question
did you check my answer here:… – stijn Nov 28 '11 at 14:54
Yes, thanks. I need much more than recognizing the running batch; ie. how about multiple instances? Can I give them a name? To kill them individually? I don't want to do it manually from Task Manager. – Nime Cloud Nov 28 '11 at 14:59
not sure what you mean - your question is about allowing a single instance. But now you're asking about multiple instances? anyway killing them can be done using taskkill or pskill – stijn Nov 28 '11 at 15:06
Single instance #1: monitor.bat Single instance #2: monitor.bat – Nime Cloud Nov 28 '11 at 15:16
that's not a single instance of the batch file itself.. You could still use the title trick if you set the titles to mybatch mybatch etc. Or resort to text files in which you keep a list of those which is better in the long run. – stijn Nov 28 '11 at 15:36

This is rather difficult from a batch file standpoint, mainly because there is no guaranteed method for a batchfile to detect instances across processes.

IMO, I think you are using the wrong tool. While, yes, it is a challenge, the more important concern is "Does it work?"

I run batch file in a scheduled time.

This tells me you should be using a scheduling program, like Task Scheduler. Task Scheduler will guarantee there is only one instance of your file, even if it is running on another user.

For example, if you run the task every 30 minutes, you configure the task to run for a duration of 30 minutes. Then you set the "if task is already running" setting to "do not create a new instance." Or you have to option of "kill the old one", "Run another instance", or "Start a new task as soon as the old one is done".

For Vista and up:
For Xp and up:

The challenging method is to create states.

  1. Your batch file enters execution
  2. Your batch file loops
  3. Your batch file ends

You can create an arbitrary file in %allusersprofile%, like >>Startmybatchfile.txt echo 1 for each state, then check if it exists. It will also help with trouble shooting. But don't delete the file at the end. Just change it to End State. That way it's deterministic if your batch file has truly finished and no longer running.

I would not use a global variable as it requires admin privileges to run.

You could also use the %temp% variable as but that changes from user to user. I guess that isn't a concern if you are a single login user machine.

share|improve this answer
If all instances are terminated then TS starts a new instance. That's why I use TS. Plus when OS starts, TS creates the first instance, etc. – Nime Cloud Nov 29 '11 at 7:24
up vote 3 down vote accepted

This is my latest and most trusted script:

set "started="
2>nul (
 9>"%~f0.lock" (
  set "started=1"
  call :start
@if defined started (
    del "%~f0.lock" >nul 2>nul
) else (
    echo Process aborted: "%~f0" is already running
    @ping localhost > nul

exit /b

cd /d %~dp0
share|improve this answer
What is happening in this script? Can we use it in multiple batch scripts? – Angelina Apr 8 at 13:16

The best way I've found to do this is to set the title on a batch script.

From there you can use tasklist to query the count of running processes by the title name. The below code snippet anything below process_count=2 means the process is not running, 3 means exactly 1 instance is running, and if above 3, there's more than 3 processes running.

Hackish, but batch is what it is.

For a continuously Looping script, I'm not smart enough to think of a way to write the start time to the title field and query that from another batch script. I have thought of copying and renaming the file-name with the time then executing that, but to me anything but a direct query is more mess than it's worth.

Yeah I can drop to text file, but I'm worried about cache corruption.

@REM ########################
@REM @@@@@@@@@@@@@@@@@@@@@@@@


@REM No way to inject a counter into this for statement.

@REM If one instance is running, or no instances, that's fine.  If more than one instance is running, time to exterminate.




@REM @@@@@@@@@@@@@@@@@@@@@@@@
@REM ########################

Also, for anyone interested; here's how to find the PID of the currently executing process. Now if you pass a variable into a sub-script, you can pass that variable back up the chain via text document (I think there's another way to do this too but that escapes me).

@REM @@@@@@@@@@@@@@@@@@@@@@@@
@REM ########################
@REM Leaving this here for later if needed.  This was a byproduct of a bad approach.


echo %self_pid%

@REM @@@@@@@@@@@@@@@@@@@@@@@@
@REM ########################
share|improve this answer

I just finished the batch file which one ensures both monitoring itself -the batch file- and the job file -facerecog.exe- are running smoothly. I've used hello.exe as a test probe tool, you may replace your own; ie. ping.exe, etc. When it starts without any parameter it fires another instance and quit, so you can run it as a scheduled task in specific intervals. I hope it helps someone who don't want to use advanced tools.

    @goto code

    @REM RunMagick for FaceRecog
    @REM Runs FaceRecog forever
    @REM Author Emin Akbulut
    @REM 29/11/2011
    @REM This code is freeware

    @CD C:\NET\FaceRecog

    set jobexe=FaceRecog.exe
    set remotehost=
    set remoteport=1333
    @REM Timeout for response of the batch, in seconds
    set /a timeout=120
    set batchtitle=Monitoring FaceRecog...

    @if NOT exist "stopwatch.exe" (
    @echo. stopwatch.exe is missing!
    @ping localhost > nul
    goto end

    @if "%1" == "/monitor" goto monitor
    @if "%1" == "/stop" goto request-stop
    @if "%1" == "/force-stop" goto stop

    tasklist /v /fi "IMAGENAME eq cmd.exe" | find /I /c "%batchtitle%"
    @if "%ERRORLEVEL%" == "0" goto batch-instance-found
    goto start

    @REM Check the previous instance is healthy/responsive or not
    stopwatch stop < pulse.log > elapsed.log
    set /a elapsed=999
    for /F %%a in ('type elapsed.log') do set /a elapsed=%%a
    if %elapsed% gtr %timeout% (
    taskkill /F /FI "WINDOWTITLE eq %batchtitle%*"
    goto start
    ) else (
    @echo Already running...
    @ping localhost > nul
    goto end

    del elapsed.log

    @goto monitor

    @REM Test FaceRecog process
    tasklist | Find "FaceRecog.exe"
    @If Not ErrorLevel 1 Goto monitor

    taskkill /f /im:conime.exe
    @PING -n 1 -w 1000 >NUL
    start FaceRecog.exe
    @REM Take a breathe
    @PING -n 1 -w 1000 >NUL
    @goto run-job

    @REM Fire another instance with /monitor command and exit
    start "%batchtitle%" /low /I %0 /monitor
    goto end

    @REM Stop the job
    taskkill /F /IM:%jobexe%
    @REM Stop the batch
    taskkill /F /FI "WINDOWSTITLE eq %batchtitle%*"
    del stop.log > nul
    title Done
    goto end

    @REM Ask programs to quit
    @REM %jobexe% /quit
    @REM Take a breathe
    @ping localhost > nul
    stopwatch start > stop.log
    goto end

    stopwatch start > pulse.log
    @REM Test /stop requested
    @if exist stop.log goto stop
    @REM Test FaceRecog process
    tasklist | Find "%jobexe%"
    @If Not ErrorLevel 0 Goto run-job

    @Echo Shorttest...
    hello.exe %remotehost% %remoteport% | Find "Version" 
    @If Not ErrorLevel 1 Goto job-ok

    @REM No response, crashed?
    tasklist | Find "WerFault.exe"
    @If ErrorLevel 1 Goto longcheck
    taskkill /F /IM:WerFault.exe
    @goto shorttest

    @Echo Longtest...
    @REM Last check, maybe FaceRecog was busy
    hello.exe %remotehost% %remoteport% | Find "Version" 
    @If Not ErrorLevel 1 Goto job-ok

    @REM Kill non-responsive FaceRecog process and wait for a while to auto-revive
    taskkill /F /IM:%jobexe%

    @echo OK
    @REM 10 seconds to wait then loop again
    @PING -n 1 -w 10000 >NUL
    @goto monitor


Thanks stijn for his great comment. Thanks surfasb for his warning about Scheduled Task that already running.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.