Implement unique application instance checks

This commit is contained in:
Kovid Goyal 2008-03-18 22:16:06 +00:00
parent 5206b38920
commit ef64ca609e
3 changed files with 41 additions and 3 deletions

View File

@ -18,7 +18,8 @@ __docformat__ = "epytext"
__author__ = "Kovid Goyal <kovid@kovidgoyal.net>"
__appname__ = 'libprs500'
import sys, os, logging, mechanize, locale, copy, cStringIO, re, subprocess, textwrap
import sys, os, logging, mechanize, locale, copy, cStringIO, re, subprocess, \
textwrap, atexit
from gettext import GNUTranslations
from math import floor
from optparse import OptionParser as _OptionParser
@ -409,3 +410,34 @@ def relpath(target, base=os.curdir):
rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:]
return os.path.join(*rel_list)
_lock_file = None
def singleinstance(name):
'''
Return True if no other instance of the application identified by name is running,
False otherwise.
@param name: The name to lock.
@type name: string
'''
if iswindows:
from win32event import CreateMutex
from win32api import CloseHandle, GetLastError
from winerror import ERROR_ALREADY_EXISTS
mutexname = 'mutexforsingleinstanceof'+__appname__+name
mutex = CreateMutex(None, False, mutexname)
if mutex:
atexit.register(CloseHandle, mutex)
return not GetLastError() == ERROR_ALREADY_EXISTS
else:
import fcntl
global _lock_file
path = os.path.expanduser('~/.'+__appname__+'_'+name+'.lock')
try:
f = open(path, 'w')
fcntl.lockf(f.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
_lock_file = f
return True
except IOError:
return False
return True

View File

@ -1009,11 +1009,17 @@ class Main(MainWindow, Ui_MainWindow):
def main(args=sys.argv):
from PyQt4.Qt import QApplication
from libprs500 import singleinstance
pid = os.fork() if islinux else -1
if pid <= 0:
app = QApplication(args)
QCoreApplication.setOrganizationName(ORG_NAME)
QCoreApplication.setApplicationName(APP_UID)
if not singleinstance('main GUI'):
QMessageBox.critical(None, 'Cannot Start '+__appname__,
'<p>%s is already running.</p>'%__appname__)
return 1
initialize_file_icon_provider()
try:
main = Main()

View File

@ -82,7 +82,7 @@ def _lock(path):
def _connect(path):
if isinstance(path, unicode):
path = path.encode('utf-8')
_lock(path)
#_lock(path)
conn = sqlite.connect(path, detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES)
conn.row_factory = lambda cursor, row : list(row)
conn.create_aggregate('concat', 1, Concatenate)