Blog

Recent Posts
Spam Filtering BitTorrent Library 0.6 Released New Project New Site Layout and Code Better iPhone/iPod Touch Automount
Archive
July, 2008June, 2008May, 2008April, 2008March, 2008February, 2008January, 2008December, 2007 Older
Recent Listening
Loading...
by

Command Line Mutex

Windows batch commands, by default, don't provide any easy way to fork a task (tasks can be forked using the "start" command) only if the task is not already started. This little batch script can be used to launch an executable only when an image of the same name is not already running. I've used it for a bunch of batch scripts I wrote to manage workspaces using Launchy. I call it "startex" as in "start exclusively".

@echo off

rem Checks to see if a task is running and stores the number of instances that were found
set PROCESSCOUNT=0
for /F usebackq %%i in (`tasklist ^| find /C "%~n1%~x1"`) do (
set PROCESSCOUNT=%%i
)

rem Depending on how we went, launch the task
if %PROCESSCOUNT%==0 start %1

This method also gets around some problems with the way Windows batch files store and access environmental variables, so it makes it very easy to launch exclusive tasks along side regular tasks. Use it like so:

startex C:\PROGRA~1\MID05A~1\Common7\IDE\devenv.exe

You may have problems if you try to specify parameters for the task, but I'm not sure since I don't need to do that for my purposes.

Link to this article | Make a Comment
Tags: Windows, Batch Scripting

Make a Comment