Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure a single instance of an application in Linux

I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this.

I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.

like image 520
Matt Green Avatar asked Oct 21 '08 01:10

Matt Green


People also ask

What is a single instance application?

A Single Instance application is an application that limits the program to run only one instance at a time. This means that you cannot open the same program twice.


2 Answers

The Right Thing is advisory locking using flock(LOCK_EX); in Python, this is found in the fcntl module.

Unlike pidfiles, these locks are always automatically released when your process dies for any reason, have no race conditions exist relating to file deletion (as the file doesn't need to be deleted to release the lock), and there's no chance of a different process inheriting the PID and thus appearing to validate a stale lock.

If you want unclean shutdown detection, you can write a marker (such as your PID, for traditionalists) into the file after grabbing the lock, and then truncate the file to 0-byte status before a clean shutdown (while the lock is being held); thus, if the lock is not held and the file is non-empty, an unclean shutdown is indicated.

like image 76
Charles Duffy Avatar answered Sep 19 '22 13:09

Charles Duffy


Complete locking solution using the fcntl module:

import fcntl pid_file = 'program.pid' fp = open(pid_file, 'w') try:     fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError:     # another instance is running     sys.exit(1) 
like image 30
zgoda Avatar answered Sep 20 '22 13:09

zgoda