コード例 #1
0
 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)
コード例 #2
0
ファイル: komodo.py プロジェクト: zhuyue1314/KomodoEdit
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)
コード例 #3
0
ファイル: ko.py プロジェクト: zhuyue1314/KomodoEdit
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)
コード例 #4
0
    def OnExit(self):
        #設定の保存やリソースの開放など、終了前に行いたい処理があれば記述できる
        #ビューへのアクセスや終了の抑制はできないので注意。

        if globalVars.app.config.getboolean(
                "player", "fadeOutOnExit", False
        ) and globalVars.play.getStatus() == PLAYER_STATUS_PLAYING:
            while globalVars.play.setVolumeByDiff(-2):
                time.sleep(0.07)
        globalVars.play.exit()
        m3uManager.dumpHistory()
        globalVars.app.config.write()
        try:
            lampPipe.stopPipeServer()
        except:
            pass
        if self.mutex != 0:
            try:
                win32event.ReleaseMutex(self.mutex)
            except:
                pass
            self.mutex = 0

        # アップデート
        globalVars.update.runUpdate()

        #戻り値は無視される
        return 0
コード例 #5
0
ファイル: lamp.py プロジェクト: actlaboratory/LAMP
def exchandler(type, exc, tb):
    msg = traceback.format_exception(type, exc, tb)
    print("".join(msg))
    try:
        f = open("errorLog.txt", "a")
        f.writelines(msg)
        f.close()
    except:
        pass

    # パイプとミューテックスの終了
    try:
        import lampPipe, globalVars
        lampPipe.stopPipeServer()
        win32event.ReleaseMutex(globalVars.app.mutex)
    except:
        pass

    if hasattr(sys, "frozen") == False:
        winsound.Beep(1500, 100)
        winsound.Beep(1500, 100)
        winsound.Beep(1500, 300)
    else:
        simpleDialog.winDialog(
            "error",
            "An error has occured. Contact to the developer for further assistance. Detail:"
            + "\n".join(msg[-2:]))
    os._exit(1)
コード例 #6
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)
コード例 #7
0
 def OnDestroy(self, hwnd, msg, wparam, lparam):
     nid = (self.hwnd, 0)
     win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, nid)
     self._Terminate()
     win32event.ReleaseMutex(self._hActiveMutex)
     win32api.CloseHandle(self._hActiveMutex)
     # Terminate the app.
     win32gui.PostQuitMessage(0)
コード例 #8
0
 def release(self):
     '''
     Release an acquired mutex. Raises IOError on error.
     '''
     if is_windows():
         win32event.ReleaseMutex(self.handle)  # pylint: disable=no-member
     else:
         fcntl.flock(self.handle, fcntl.LOCK_UN)
     self.acquired = False
コード例 #9
0
ファイル: os_windows.py プロジェクト: p4hm/ambari
 def write(self, data):
     #Ensure that the output is thread-safe when writing from 2 separate streams into the same file
     #  (typical when redirecting both stdout and stderr to the same file).
     win32event.WaitForSingleObject(self.hMutexWrite, win32event.INFINITE)
     try:
         self.stream.write(data)
         self.stream.flush()
     finally:
         win32event.ReleaseMutex(self.hMutexWrite)
コード例 #10
0
ファイル: glock.py プロジェクト: nkaul/ocp-checkbox
    def release(self, skip_delete=False):
        ''' Unlocks. (caller must own the lock!)

            @param skip_delete: don't try to delete the file. This can
                be used when the original filename has changed; for
                instance, if the lockfile is erased out-of-band, or if
                the directory it contains has been renamed.

            @return: The lock count.
            @exception IOError: if file lock can't be released
            @exception NotOwner: Attempt to release somebody else's lock.
        '''
        if not self.is_locked:
            return
        if not skip_delete:
            if self.logger:
                self.logger.debug('Removing lock file: %s', self.fpath)
            os.unlink(self.fpath)
        elif self.logger:
            # At certain times the lockfile will have been removed or
            # moved away before we call release(); log a message because
            # this is unusual and could be an error.
            self.logger.debug('Oops, my lock file disappeared: %s', self.fpath)
        if _windows:
            if ctypes:
                result = ctypes.windll.kernel32.ReleaseMutex(self.mutex.handle)
                if not result:
                    raise NotOwner("Attempt to release somebody else's lock")
            else:
                try:
                    win32event.ReleaseMutex(self.mutex)
                    #print "released mutex"
                except pywintypes.error as e:
                    errCode, fctName, errMsg = e.args
                    if errCode == 288:
                        raise NotOwner(
                            "Attempt to release somebody else's lock")
                    else:
                        raise GlobalLockError('%s: err#%d: %s' %
                                              (fctName, errCode, errMsg))
        else:
            # First release the local (inter-thread) lock:
            try:
                self.threadLock.release()
            except AssertionError:
                raise NotOwner("Attempt to release somebody else's lock")

            # Then release the global (inter-process) lock:
            try:
                fcntl.flock(self.fdlock, fcntl.LOCK_UN)
            except IOError:  # (errno 13: permission denied)
                raise GlobalLockError('Unlock of file "%s" failed\n' %
                                      self.name)
        self.is_locked = False
コード例 #11
0
ファイル: app.py プロジェクト: actlaboratory/LAMP
 def __del__(self):
     try:
         lampPipe.stopPipeServer()
     except:
         pass
     if self.mutex != 0:
         try:
             win32event.ReleaseMutex(self.mutex)
         except:
             pass
         self.mutex = 0
コード例 #12
0
ファイル: IPC.py プロジェクト: galaxy001/libtorrent
    def discover_sic_socket(self):
        takeover = 0

        # mutex exists and has been opened (not created, not locked).
        # wait for it so we can read the file
        r = win32event.WaitForSingleObject(self.mutex, win32event.INFINITE)

        # WAIT_OBJECT_0 means the mutex was obtained
        # WAIT_ABANDONED means the mutex was obtained, and it had previously been abandoned
        if (r != win32event.WAIT_OBJECT_0) and (r !=
                                                win32event.WAIT_ABANDONED):
            raise BTFailure(
                _("Could not acquire global mutex lock for controlsocket file!"
                  ))

        filename = self._get_sic_path()
        try:
            f = open(filename, "r")
            self.port = int(f.read())
            f.close()
        except:
            if (r == win32event.WAIT_ABANDONED):
                self.log(
                    WARNING,
                    _("A previous instance of BT was not cleaned up properly. Continuing."
                      ))
                # take over the role of master
                takeover = 1
            else:
                self.log(WARNING, (_(
                    "Another instance of BT is running, but \"%s\" does not exist.\n"
                ) % filename) + _("I'll guess at the port."))
                try:
                    self.port = CONTROL_SOCKET_PORT
                    self.send_command('no-op')
                    self.log(WARNING, _("Port found: %d") % self.port)
                    try:
                        f = open(filename, "w")
                        f.write(str(self.port))
                        f.close()
                    except:
                        traceback.print_exc()
                except:
                    # this is where this system falls down.
                    # There's another copy of BitTorrent running, or something locking the mutex,
                    # but I can't communicate with it.
                    self.log(WARNING, _("Could not find port."))

        # we're done reading the control file, release the mutex so other instances can lock it and read the file
        win32event.ReleaseMutex(self.mutex)

        return takeover
コード例 #13
0
ファイル: IPC.py プロジェクト: galaxy001/libtorrent
 def stop(self):
     if self.master:
         r = win32event.WaitForSingleObject(self.mutex, win32event.INFINITE)
         filename = self._get_sic_path()
         try:
             os.remove(filename)
         except OSError, e:
             # print, but continue
             traceback.print_exc()
         self.master = 0
         win32event.ReleaseMutex(self.mutex)
         # close it so the named mutex goes away
         win32api.CloseHandle(self.mutex)
         self.mutex = None
コード例 #14
0
 def release(self):
     # unlock
     assert self._mylock
     if os.name == 'nt':
         win32event.ReleaseMutex(self._mutex)
         # Error code 123?
         #lasterror = win32api.GetLastError()
         #if lasterror != 0:
         #    raise IOError( _("Could not release mutex %s due to "
         #                     "error windows code %d.") %
         #                    (self._name,lasterror) )
     elif os.name == 'posix':
         self._mylock = False
         if not os.path.exists(self._path):
             raise IOError(_("Non-existent file: %s") % self._path)
         flock(self._mutex.fileno(), fcntl.LOCK_UN)
         self._mutex.close()
コード例 #15
0
        def exit(self):
            # Grab the lock.
            lock = win32event.CreateMutex(None, 0, _gCommandmentsLockName)
            win32event.WaitForSingleObject(lock, win32event.INFINITE)
            # Send __exit__ commandment.
            f = open(_gCommandmentsFileName, 'a')
            f.write("__exit__\n")
            f.close()
            # Signal hat 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)

            self.join()
コード例 #16
0
ファイル: ko.py プロジェクト: zhuyue1314/KomodoEdit
        def run(self):
            lock = win32event.CreateMutex(None, 0, gCommandmentsLockName)
            existing = os.path.exists(gCommandmentsFileName)
            newCommandments = win32event.CreateEvent(None, 0, existing,
                                                     gCommandmentsEventName)

            while 1:
                # Wait for new commandments.
                rv = win32event.WaitForSingleObject(newCommandments,
                                                    win32event.INFINITE)
                if rv == win32event.WAIT_OBJECT_0:
                    retval = 1
                else:
                    raise "Error waiting for new commandments: %r" % rv
                # Grab the lock.
                win32event.WaitForSingleObject(lock, win32event.INFINITE)
                # Consume the commandments.
                f = open(gCommandmentsFileName, 'r')
                cmds = []
                for line in f.readlines():
                    if line[-1] == '\n':
                        line = line[:-1]
                    if line.strip(): # skip empty lines
                        cmds.append(line)
                f.close()
                os.unlink(gCommandmentsFileName)
                # Reset the "new commandments" event.
                win32event.ResetEvent(newCommandments)
                # Release the lock.
                win32event.ReleaseMutex(lock)
                # Handle the commandments.
                exit = 0
                for cmd in cmds:
                    log.info("handle: %r", cmd)
                    if cmd == "__exit__":
                        exit = 1
                        break
                if exit:
                    break

            win32api.CloseHandle(newCommandments)
            win32api.CloseHandle(lock)
コード例 #17
0
        def run(self):
            lock = win32event.CreateMutex(None, 0, _gCommandmentsLockName)
            newCommandments = win32event.CreateEvent(None, 1, 0,
                                                     _gCommandmentsEventName)

            while 1:
                # Wait for new commandments.
                rv = win32event.WaitForSingleObject(newCommandments,
                                                    win32event.INFINITE)
                if rv == win32event.WAIT_OBJECT_0:
                    retval = 1
                else:
                    raise "Error waiting for new commandments: %r" % rv
                # Grab the lock.
                win32event.WaitForSingleObject(lock, win32event.INFINITE)
                # Consume the commandments.
                f = open(_gCommandmentsFileName, 'r')
                cmds = []
                for line in f.readlines():
                    if line.endswith('\n'):
                        cmds.append( line[:-1] )
                f.close()
                os.unlink(_gCommandmentsFileName)
                # Reset the "new commandments" event.
                win32event.ResetEvent(newCommandments)
                # Release the lock.
                win32event.ReleaseMutex(lock)
                # Handle the commandments.
                exit = 0
                for cmd in cmds:
                    print "command handler: cmd=%r" % cmd
                    if cmd == "__exit__":
                        exit = 1
                        break
                if exit:
                    break

            win32api.CloseHandle(newCommandments)
            win32api.CloseHandle(lock)
コード例 #18
0
ファイル: app.py プロジェクト: actlaboratory/LAMP
    def OnExit(self):
        #設定の保存やリソースの開放など、終了前に行いたい処理があれば記述できる
        #ビューへのアクセスや終了の抑制はできないので注意。

        m3uManager.dumpHistory()
        globalVars.app.config.write()
        try:
            lampPipe.stopPipeServer()
        except:
            pass
        if self.mutex != 0:
            try:
                win32event.ReleaseMutex(self.mutex)
            except:
                pass
            self.mutex = 0

        # アップデート
        globalVars.update.runUpdate()

        #戻り値は無視される
        return 0
コード例 #19
0
                break
    elif close_watch_method == "playnite_mutex":
        while True:
            try:
                #Instance is spelled wrong in the Playnite source code, this may need to be fixed someday
                #for now it must be spelled Instace
                playnite_mutex_handle = win32event.OpenMutex(
                    win32event.SYNCHRONIZE, False, "PlayniteInstaceMutex")
                break
            except Exception as e:
                print(f"Exception attempting to open Playnite mutex:{e}")
                sleep(0.1)
        #Playnite creates and locks a mutex so if we can lock the mutex it means Playnite has quit
        win32event.WaitForSingleObject(playnite_mutex_handle, 0xffffffff)
        #We need to tear down the mutex or Playnite won't start again
        win32event.ReleaseMutex(playnite_mutex_handle)
        win32api.CloseHandle(playnite_mutex_handle)

    else:
        print(
            "No valid close_watch_method in the config. Press Enter when you're done."
        )
        input()

# Terminate background and launch session_end programs, if they're available
kill_processes(cfg_bg_paths)
launch_processes(cfg_end_paths)

# Restore original resolution
if skip_res_reset == False:
    print('Restoring original resolution.')
コード例 #20
0
    cfg = get_configuration_alexnet()
prepare_detect(cfg, False)

model = load_model(model_path)
# make evaluator
evaluator = FasterRCNN_Evaluator(model, cfg)
# prepare main image detect. BCZ It is too slow first,second time.
od.predict_dummy_image(model, cfg, evaluator)
od.predict_dummy_image(model, cfg, evaluator)
od.predict_dummy_image(model, cfg, evaluator)
#od.predict_dummy_image(model,  cfg,evaluator)
#od.predict_dummy_image(model,  cfg,evaluator)
# model load finished
win32event.WaitForSingleObject(mutex, win32event.INFINITE)
shm.write(bytes(str(1), "ascii"))
win32event.ReleaseMutex(mutex)
#=======================================================================================================================
while (ctypes.windll.user32.IsWindow(hwnd)):
    win32event.WaitForSingleObject(mutex, win32event.INFINITE)
    shm.seek(0)
    run_type = shm.read(1)
    if (run_type == b'2'):
        img_path = shm.read(256).decode('cp949')
        img_path = img_path.split('\0', 1)[0]
        # detect
        regressed_rois, cls_probs = od.predict_single_image(
            model, img_path, cfg, evaluator)
        # fix roi
        img = imreadEX(img_path)
        height, width = img.shape[:2]
        scale = 850.0 / max(width, height)
コード例 #21
0
ファイル: ko.py プロジェクト: zhuyue1314/KomodoEdit
def releaseMutex(mutex):
    if sys.platform == "win32":
        win32event.ReleaseMutex(mutex)
        win32api.CloseHandle(mutex)
    else:
        fcntl.lockf(mutex, fcntl.LOCK_UN)
コード例 #22
0
 def release(self):
     return win32event.ReleaseMutex(self.mutex)
コード例 #23
0
 def closeMutex(self):
     if self.MutexHndle:
         win32event.ReleaseMutex(self.MutexHndle)
         self.MutexHndle = None
コード例 #24
0
        KILL_EVENT.close()
    exit(1)


with SafeExecutionPack(MEM, MUTEX, RECOGNITION_EVENT, RESULT_TAKEN_EVENT, KILL_EVENT):
    exception_counter = 0
    while True:
        try:
            w = win32event.WaitForSingleObject(KILL_EVENT, 100)
            if w == win32event.WAIT_OBJECT_0:
                print('Kill event accepted')
                break
            img = event_generator_proc.get_webcam_image()
            if not event_generator_proc.is_passport(img):
                continue
            w = win32event.WaitForSingleObject(MUTEX, 0)
            if w == win32event.WAIT_TIMEOUT:
                continue
            data = event_generator_proc.recognition(img)
            event_generator_proc.json_to_mem(MEM_BUF, data)
            win32event.ReleaseMutex(MUTEX)
            win32event.SetEvent(RECOGNITION_EVENT)
            w = win32event.WaitForSingleObject(RESULT_TAKEN_EVENT, 10000)
            if w == win32event.WAIT_TIMEOUT:
                print('Missing recognized passport, data:\n')
        except Exception as e:
            print('Exception', e)
            exception_counter += 1
            if exception_counter == 5:
                print('TOO MUCH EXCEPTIONS')
                break
コード例 #25
0
ファイル: IPC.py プロジェクト: galaxy001/libtorrent
        filename = self._get_sic_path()
        (path, name) = os.path.split(filename)
        try:
            os.makedirs(path)
        except OSError, e:
            # 17 is dir exists
            if e.errno != 17:
                BTFailure(_("Could not create application data directory!"))
        f = open(filename, "w")
        f.write(str(self.port))
        f.close()

        # we're done writing the control file, release the mutex so other instances can lock it and read the file
        # but don't destroy the handle until the application closes, so that the named mutex is still around
        win32event.ReleaseMutex(self.mutex)

    def discover_sic_socket(self):
        takeover = 0

        # mutex exists and has been opened (not created, not locked).
        # wait for it so we can read the file
        r = win32event.WaitForSingleObject(self.mutex, win32event.INFINITE)

        # WAIT_OBJECT_0 means the mutex was obtained
        # WAIT_ABANDONED means the mutex was obtained, and it had previously been abandoned
        if (r != win32event.WAIT_OBJECT_0) and (r !=
                                                win32event.WAIT_ABANDONED):
            raise BTFailure(
                _("Could not acquire global mutex lock for controlsocket file!"
                  ))
コード例 #26
0
        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
    except IOError, e:
        print('Could not write to the log file %s. Error: %s' %
              (logfile, str(e)))

    # release our synchronisation mutex
    if sys.platform.startswith("win") and hMutex is not None:
        try:
            win32event.ReleaseMutex(hMutex)
        except win32api.error, e:
            print('Could not release mutex %s Error: %s' % (name, str(e)))


def GetDBInfo(filename):
    try:
        # first 100 bytes of the file are definitely text
        f = file(filename, 'rt')
        # read first 100 bytes
        data = f.read(100)
        data = data.split(':')
        updatestr, ver, numv = data[1:4]

        # set C locale, otherwise python and wxpython complain
        locale.setlocale(locale.LC_ALL, 'C')
コード例 #27
0
ファイル: base.py プロジェクト: mikeMcoder/myRepository
 def __ReleaseMutex__(self):
     w.ReleaseMutex(self.__class__.__sMutex[self.key])
     if dbg: print("Lock Released for " + self.key)
コード例 #28
0
ファイル: komodo.py プロジェクト: zhuyue1314/KomodoEdit
def releaseKomodoStatusLock(lock):
    # No such lock used on Linux.
    if sys.platform.startswith("win"):
        win32event.ReleaseMutex(lock)
        win32api.CloseHandle(lock)
コード例 #29
0
ファイル: os_windows.py プロジェクト: p4hm/ambari
 def unlock(self):
     try:
         win32event.ReleaseMutex(self._mutex)
         return True
     except:
         return False
コード例 #30
0
 def release(self):
     win32event.ReleaseMutex(self.handle)
     self.locked = False