Allowing only one instance of a script?

A

Ali

Hi,

I have a script which I double-click to run. If i double-click it
again, it will launch another instance of the script.

Is there a way to allow only one instance of a script, so that if
another instance of the script is launched, it will just return with an
error.

Thanks

Regards,
Ali
 
T

Thomas Guettler

Am Wed, 22 Jun 2005 23:49:21 -0700 schrieb Ali:
Hi,

I have a script which I double-click to run. If i double-click it
again, it will launch another instance of the script.

Is there a way to allow only one instance of a script, so that if
another instance of the script is launched, it will just return with an
error.

Hi,

Create a file which contains the PID (process ID) of
the current process in a directory. If the file
already exists, the file is running.

If your script dies without removing the pid-file, you
need to look during the start if the PID which is in the
file is sill alive.

There is a small race condition between os.path.exists()
and writing the file. If you want to be 100% sure you need
to use file locking.

HTH,
Thomas
 
G

Grant Edwards

Create a file which contains the PID (process ID) of
the current process in a directory. If the file
already exists, the file is running.

That's how it's usually done.
If your script dies without removing the pid-file, you need to
look during the start if the PID which is in the file is sill
alive.

There is a small race condition between os.path.exists()
and writing the file.

That's why it's pointless to call os.path.exists().
If you want to be 100% sure you need to use file locking.

I've never seen it done that way.

The standard method is to use open() with flags O_CREAT|O_EXCL.
If the open() is sucessful, then you have the lock. If it
fails, somebody else already has the lock.

Another method is to create a temp file containing the PID and
then call link() to rename it.

Both open() and link() are atomic operations, so there's no
race condition.
 
G

Grant Edwards

...unless you're running under NFS.

I think read somewhere than NFS 3 handles the open with
CREAT+EXCL in an atomic manner (older versions didn't). I don't
know about link.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top