--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/releasing/blocks/framework/src/Blocks/singleinstance.py Thu Sep 02 15:02:14 2010 +0800
@@ -0,0 +1,84 @@
+#
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:
+# Create only single instance of application/process
+#
+
+import os
+import tempfile
+import logging
+import platform
+
+if platform.system() == "Windows":
+ from win32event import CreateMutex, WaitForSingleObject, ReleaseMutex, INFINITE
+ from win32api import CloseHandle, GetLastError
+ from winerror import ERROR_ALREADY_EXISTS
+
+from Blocks.filelock import FileLock
+
+class SingleInstanceWindows(object):
+ ''' Single instance implemented with mutex '''
+
+ def __init__(self, identifier, path=False, lockFileName=None):
+ ''' lockFileName not used in this implementation '''
+ if path:
+ identifier = identifier.replace("\\", "/")
+ self._identifier = "Global\\" + identifier
+ logging.log(logging.DEBUG, "SingleInstanceWindows mutex identifier: %s", self._identifier)
+ self._mutex = CreateMutex(None, True, self._identifier)
+ self.mutexError = GetLastError()
+
+ def alreadyRunning(self):
+ return (self.mutexError == ERROR_ALREADY_EXISTS)
+
+ def waitRelease(self, timeout=None):
+ timeout = INFINITE if timeout is None else timeout
+ if self.alreadyRunning():
+ WaitForSingleObject(self._mutex, timeout)
+
+ def release(self):
+ if self._mutex:
+ ReleaseMutex(self._mutex)
+ CloseHandle(self._mutex)
+
+class SingleInstanceFilelock(FileLock):
+ ''' Single instance implemented with file locking '''
+ def __init__(self, identifier, path=False, lockFileName=".lock"):
+ if path:
+ try:
+ os.makedirs(identifier)
+ except OSError: # Dir exists already?
+ pass
+ lockfile = os.path.join(identifier, lockFileName)
+ else:
+ lockfile = os.path.join(tempfile.gettempdir(), identifier)
+ FileLock.__init__(self, lockfile)
+
+ def alreadyRunning(self):
+ return not self.acquire()
+
+ def waitRelease(self, timeout=None):
+ self.acquire(timeout)
+
+if platform.system() == "Windows":
+ SingleInstance = SingleInstanceWindows
+else:
+ SingleInstance = SingleInstanceFilelock
+
+if __name__ == "__main__":
+ si = SingleInstance("c:\\temp", True)
+ print "Running:", si.alreadyRunning()
+ raw_input("Enter to release/start waiting")
+ si.waitRelease()
+ raw_input("Enter to quit")
\ No newline at end of file