[Tutor] Watch and control access to an executable

Alan Gauld alan.gauld at freenet.co.uk
Sat Apr 8 15:10:31 CEST 2006

> Desktop to the executable). The problem is, only *one* person at a time
> should run the program.

> Now here's my solution:
> 1. Create a program let's call it 'myProg' that spawns 'otherProg'.
> 2. 'myProg' will utilize a config file.
> 3. When 'myProg' is started it looks in the config file to see if
> 'otherProg' is running.

The usual way of doing this is simply to create an empty file
when the program starts and delete it when the program closes
In python:

# File : exRun.py
''' usage python exRun.py  foo.exe

   prevents more than one copy of the guarded program running

import os, sys

if len(sys.argv) != 2:
   print "Usage: python exRun.py <application name>"

prog = sys.argv[1]
fname = prog+'running.dat'
      open(fname,'w').close()   # create an empty file.
except IOError:
      print  prog, 'is already running, try again later'

> 4. If 'otherProg' is not running, start it and write to the config file
> that 'otherProg' is running (also write who is running it).
> 5. 'myProg' continues to run on the user's computer, continuously
> checking the PID (of 'otherProg') to see if the process is still alive.
> 6. When we don't find the PID anymore, write to the config file that
> 'otherProg' isn't running.
> 7. Shutdown 'myProg'.

The design above will work too of course but uses more CPU cycles
and may be slightly harder to fix if the machine crashes while the app
is running sincve the open config file could be corrupted.

> Now in step #3 above - if 'myProg' reads the config file and finds that
> the 'otherProg' is currently running, the user is warned that 'The
> program is currently in use by <insert username from config file>!' And
> 'otherProg' is not started.

The current user name can be obtained from getpass.getuser() if you need it.

> Couple of other things.....
> 1. I'm taking 'myProg' and creating a single-file executable using py2exe.

Thats fair enough

> 2. 'myProg.exe' and the config file live on the network in the same
> directory as 'otherProg'.

There's no real need for that. My version usually lives in a common
area since it can be used to control multiple apps, and it usually writes
its file into a semi-hidden folder to avoid unscrupulous users deleting
the file!.

> 3. User's have a shortcut on the Desktop to 'myProg.exe' instead of
> 'otherProg'.

Yes, or in my case several shortcuts with the app names hard coded
in the shortcut.

> BTW, I've never stopped to consider if there was a simple 'Windows
> networking / permissions' type solution to the problem. I just went
> straight to Python :-)

You can do it all using DOS style BAT files if you use my approach.

> Here's my code. I'd appreciate any critiques!

Its longer than mine :-)

Alan G
Author of the learn to program web tutor

More information about the Tutor mailing list