Python fcntl.lockf方法代码示例

本文整理汇总了Python中fcntl.lockf方法的典型用法代码示例。如果您正苦于以下问题:Python fcntl.lockf方法的具体用法?Python fcntl.lockf怎么用?Python fcntl.lockf使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块fcntl的用法示例。

在下文中一共展示了fcntl.lockf方法的23个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: release

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def release(self):
        """Release the lock by deleting `self.lockfile`."""
        if not self._lock.is_set():
            return False
        try:
            fcntl.lockf(self._lockfile, fcntl.LOCK_UN)
        except IOError:  # pragma: no cover
            pass
        finally:
            self._lock.clear()
            self._lockfile = None
            try:
                os.unlink(self.lockfile)
            except (IOError, OSError):  # pragma: no cover
                pass
            return True 
开发者ID:TKkk-iOSer,项目名称:wechat-alfred-workflow,代码行数:20,代码来源:util.py


示例2: unlock_file

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def unlock_file(self, name):
        f = self.locks.get(name)
        if not f:
            self.log(DEBUG, "unlock_file: %s not locked", name)
            return
        # XXXX does this create a possible race condition?
        if 0:
            try:
                os.unlink(name)
            except:
                pass
        status = fcntl.lockf(f, fcntl.LOCK_UN)
        f.close()
        del self.locks[name]
        return status 
开发者ID:rucio,项目名称:rucio,代码行数:18,代码来源:pcache.py


示例3: bounce_lock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def bounce_lock(name):
    """Acquire a bounce lockfile for the name given. The name should generally
    be the service namespace being bounced.
    This is a contextmanager. Please use it via 'with bounce_lock(name):'.
    :param name: The lock name to acquire"""
    lockfile = "/var/lock/%s.lock" % name
    with open(lockfile, "w") as fd:
        remove = False
        try:
            fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            remove = True
            yield
        except IOError:
            raise LockHeldException("Service %s is already being bounced!" % name)
        finally:
            if remove:
                os.remove(lockfile) 
开发者ID:Yelp,项目名称:paasta,代码行数:21,代码来源:bounce_lib.py


示例4: lock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def lock(self):
        """
        Locks the package to avoid concurrent operations on its shared
        resources.
        Currently, the only resource shared among scripts executed from
        different directories is the repository.
        """
        if not self.locking_enabled:
            LOG.debug("This package has no shared resources to lock")
            return
        LOG.debug("Checking for lock on file {}.".format(self.lock_file_path))
        self.lock_file = open(self.lock_file_path, "w")
        try:
            fcntl.lockf(self.lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError as exc:
            RESOURCE_UNAVAILABLE_ERROR = 11
            if exc.errno == RESOURCE_UNAVAILABLE_ERROR:
                LOG.info("Waiting for other process to finish operations "
                         "on {}.".format(self.name))
            else:
                raise
        fcntl.lockf(self.lock_file, fcntl.LOCK_EX) 
开发者ID:open-power-host-os,项目名称:builds,代码行数:25,代码来源:package.py


示例5: singleton

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def singleton(lockfile, text="semaphore"):
    """
    Open a lockfile exclusively.
    """
    if not lockfile.parent.exists():
        mkdir(lockfile.parent)
    try:
        if has_fcntl:
            f = open(lockfile, "w")
            fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
        else:
            if lockfile.exists():
                lockfile.unlink()
            fd = os.open(lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
            f = open(fd, "w")
        f.write(text)
    except IOError:
        return None
    return f 
开发者ID:Chia-Network,项目名称:chia-blockchain,代码行数:23,代码来源:server.py


示例6: __init__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def __init__(self, client_name):
        self.lockfile = os.path.join(get_cache_dir("client_locks"), client_name)
        logger.debug("SingleInstance lockfile: " + self.lockfile)
        if sys.platform == 'win32':
            try:
                # file already exists, we try to remove (in case previous execution was interrupted)
                if os.path.exists(self.lockfile):
                    os.unlink(self.lockfile)
                    self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
            except OSError as e:
                if e.errno == 13:
                    logger.error("Another instance is already running, quitting.")
                    sys.exit(-1)
                else:
                    raise e
        else:  # non Windows
            self.fp = open(self.lockfile, 'w')
            try:
                fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError:
                logger.error("Another instance is already running, quitting.")
                sys.exit(-1) 
开发者ID:ActivityWatch,项目名称:aw-client,代码行数:24,代码来源:singleinstance.py


示例7: main

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def main(self, test_args: dict = None):
        start_time = datetime.now()
        args = self.parser.parse_args(test_args)
        root_folder = Path(args.root_folder).absolute()
        db_path = Path(args.db_path) if args.db_path else root_folder
        if not root_folder.exists():
            root_folder.mkdir(parents=True, mode=0o700)
        setup_logging(args.log_level, args.logfile, root_folder)
        log.warning(f"gphotos-sync {__version__} {start_time}")
        args = self.fs_checks(root_folder, args)
        lock_file = db_path / "gphotos.lock"
        fp = lock_file.open("w")
        with fp:
            try:
                if os.name != "nt":
                    fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError:
                log.warning("EXITING: database is locked")
                sys.exit(0)
            log.info(self.version_string)
            # configure and launch
            # noinspection PyBroadException
            try:
                self.setup(args, db_path)
                self.start(args)
            except KeyboardInterrupt:
                log.error("User cancelled download")
                log.debug("Traceback", exc_info=True)
            except BaseException:
                log.error("\nProcess failed.", exc_info=True)
            finally:
                log.warning("Done.")
        elapsed_time = datetime.now() - start_time
        log.info("Elapsed time = %s", elapsed_time) 
开发者ID:gilesknap,项目名称:gphotos-sync,代码行数:43,代码来源:Main.py


示例8: write_pid_file

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def write_pid_file(pid_file, pid):
    import fcntl
    import stat
    try:
        fd = os.open(pid_file, os.O_RDWR | os.O_CREAT,
                     stat.S_IRUSR | stat.S_IWUSR)
    except OSError as e:
        shell.print_exception(e)
        return -1
    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    assert flags != -1
    flags |= fcntl.FD_CLOEXEC
    r = fcntl.fcntl(fd, fcntl.F_SETFD, flags)
    assert r != -1
    # There is no platform independent way to implement fcntl(fd, F_SETLK, &fl)
    # via fcntl.fcntl. So use lockf instead
    try:
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET)
    except IOError:
        r = os.read(fd, 32)
        if r:
            logging.error('already started at pid %s' % common.to_str(r))
        else:
            logging.error('already started')
        os.close(fd)
        return -1
    os.ftruncate(fd, 0)
    os.write(fd, common.to_bytes(str(pid)))
    return 0 
开发者ID:ntfreedom,项目名称:neverendshadowsocks,代码行数:32,代码来源:daemon.py


示例9: lock_file

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def lock_file(self, name, blocking=True):
        if name in self.locks:
            self.log(DEBUG, "lock_file: %s already locked", name)
            return
        try:
            f = open(name, 'w')
        except IOError as e:
            self.log(ERROR, "open: %s", e)
            return e.errno
        self.locks[name] = f
        flag = fcntl.LOCK_EX
        if not blocking:
            flag |= fcntl.LOCK_NB
        while True:
            try:
                status = fcntl.lockf(f, flag)
                break
            except IOError as e:
                if e.errno in (errno.EAGAIN, errno.EACCES) and not blocking:
                    f.close()
                    del self.locks[name]
                    return e.errno
                if e.errno != errno.EINTR:
                    status = e.errno
                    self.log(ERROR, "lockf: %s", e)
                    self.fail(106)
        return status 
开发者ID:rucio,项目名称:rucio,代码行数:30,代码来源:pcache.py


示例10: unlock_and_close

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def unlock_and_close(self):
      """Close and unlock the file using the fcntl.lockf primitive."""
      if self._locked:
        fcntl.lockf(self._fh.fileno(), fcntl.LOCK_UN)
      self._locked = False
      if self._fh:
        self._fh.close() 
开发者ID:mortcanty,项目名称:earthengine,代码行数:9,代码来源:locked_file.py


示例11: __enter__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def __enter__(self):
        self._worker_lock_dir.mkdir(exist_ok=True)
        worker_id = 0
        while True:
            self._lock_file = (self._worker_lock_dir / str(worker_id)).open('w')
            try:
                fcntl.lockf(self._lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
                return worker_id
            except OSError as e:
                if e.errno not in (errno.EAGAIN, errno.EACCES):
                    raise
            worker_id += 1 
开发者ID:PrivacyScore,项目名称:PrivacyScore,代码行数:14,代码来源:utils.py


示例12: __exit__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def __exit__(self, exc_type, exc_value, traceback):
        if self._lock_file:
            fcntl.lockf(self._lock_file.fileno(), fcntl.LOCK_UN)
            self._lock_file.close() 
开发者ID:PrivacyScore,项目名称:PrivacyScore,代码行数:6,代码来源:utils.py


示例13: lock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def lock():
    # Since Local Mode uses the same port for serving, we need a lock in order
    # to allow concurrent test execution.
    local_mode_lock_fd = open(LOCK_PATH, 'w')
    local_mode_lock = local_mode_lock_fd.fileno()
    fcntl.lockf(local_mode_lock, fcntl.LOCK_EX)
    try:
        yield
    finally:
        time.sleep(5)
        fcntl.lockf(local_mode_lock, fcntl.LOCK_UN) 
开发者ID:aws,项目名称:sagemaker-pytorch-training-toolkit,代码行数:15,代码来源:local_mode_utils.py


示例14: _lock_file

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def _lock_file(f, dotlock=True):
    """Lock file f using lockf and dot locking."""
    dotlock_done = False
    try:
        if fcntl:
            try:
                fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError, e:
                if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
                    raise ExternalClashError('lockf: lock unavailable: %s' %
                                             f.name)
                else:
                    raise
        if dotlock:
            try:
                pre_lock = _create_temporary(f.name + '.lock')
                pre_lock.close()
            except IOError, e:
                if e.errno in (errno.EACCES, errno.EROFS):
                    return  # Without write access, just skip dotlocking.
                else:
                    raise
            try:
                if hasattr(os, 'link'):
                    os.link(pre_lock.name, f.name + '.lock')
                    dotlock_done = True
                    os.unlink(pre_lock.name)
                else:
                    os.rename(pre_lock.name, f.name + '.lock')
                    dotlock_done = True
            except OSError, e:
                if e.errno == errno.EEXIST or \
                  (os.name == 'os2' and e.errno == errno.EACCES):
                    os.remove(pre_lock.name)
                    raise ExternalClashError('dot lock unavailable: %s' %
                                             f.name)
                else:
                    raise 
开发者ID:glmcdona,项目名称:meddle,代码行数:40,代码来源:mailbox.py


示例15: _unlock_file

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def _unlock_file(f):
    """Unlock file f using lockf and dot locking."""
    if fcntl:
        fcntl.lockf(f, fcntl.LOCK_UN)
    if os.path.exists(f.name + '.lock'):
        os.remove(f.name + '.lock') 
开发者ID:glmcdona,项目名称:meddle,代码行数:8,代码来源:mailbox.py


示例16: __init__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def __init__(self, args, single_app=False):
        # Ensure only one app instance is running.
        # From https://stackoverflow.com/questions/220525/
        #              ensure-a-single-instance-of-an-application-in-linux#221159
        if single_app:
            pid_file = os.path.join(SETTINGS_DIR, "restatic.pid")
            lockfile = open(pid_file, "w+")
            try:
                fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
                self.lockfile = lockfile
            except OSError:
                print("An instance of Restatic is already running.")
                sys.exit(1)
        super().__init__(args)
        self.setQuitOnLastWindowClosed(False)
        self.scheduler = RestaticScheduler(self)
        # Prepare tray and main window
        self.tray = TrayMenu(self)
        self.main_window = MainWindow(self)
        self.main_window.show()
        self.backup_started_event.connect(self.backup_started_event_response)
        self.backup_finished_event.connect(self.backup_finished_event_response)
        self.backup_cancelled_event.connect(self.backup_cancelled_event_response) 
开发者ID:Mebus,项目名称:restatic,代码行数:29,代码来源:application.py


示例17: _lock_file_posix

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def _lock_file_posix(self, path, exclusive=True):
        lock_path = path + '.lock'
        if exclusive is True:
            f_lock = open(lock_path, 'w')
            fcntl.lockf(f_lock, fcntl.LOCK_EX)
        else:
            f_lock = open(lock_path, 'r')
            fcntl.lockf(f_lock, fcntl.LOCK_SH)
        if os.path.exists(lock_path) is False:
            f_lock.close()
            return None
        return f_lock 
开发者ID:singhj,项目名称:locality-sensitive-hashing,代码行数:14,代码来源:cache.py


示例18: lock_file

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def lock_file(filename, mode=fcntl.LOCK_EX):
    lockfile = open(filename, "w")
    fcntl.lockf(lockfile, mode)
    return lockfile 
开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:6,代码来源:utils_misc.py


示例19: unlock_file

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def unlock_file(lockfile):
    fcntl.lockf(lockfile, fcntl.LOCK_UN)
    lockfile.close()
# Utility functions for dealing with external processes 
开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:8,代码来源:utils_misc.py


示例20: write_server_info

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def write_server_info(filename, port):
    pid = os.getpid()
    rank = MPI.COMM_WORLD.Get_rank()
    server_info = '{}:{}:{}:{}:{}'.format(LINE_TOKEN, rank, pid, port, LINE_TOKEN).strip()
    logger.debug("write_server_info: line %s, filename %s", server_info, filename)
    time.sleep(0.1 * rank)
    with open(filename, "a") as f:
        fcntl.lockf(f, fcntl.LOCK_EX)
        f.write(server_info + '\n')
        f.flush()
        os.fsync(f.fileno())
        fcntl.lockf(f, fcntl.LOCK_UN)
    return server_info 
开发者ID:NervanaSystems,项目名称:ngraph-python,代码行数:16,代码来源:hetr_server.py


示例21: get_rpc_port_by_rank

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def get_rpc_port_by_rank(self, rank, num_servers):
        if self.mpirun_proc is None:
            raise RuntimeError("Launch mpirun_proc before reading of rpc ports")
        if self._rpc_ports is not None:
            return self._rpc_ports[rank]
        server_info_pattern = re.compile("^" + LINE_TOKEN +
                                         ":([\d]+):([\d]+):([\d]+):" +
                                         LINE_TOKEN + "$")
        self._tmpfile.seek(0)
        while True:
            fcntl.lockf(self._tmpfile, fcntl.LOCK_SH)
            line_count = sum(1 for line in self._tmpfile if server_info_pattern.match(line))
            self._tmpfile.seek(0)
            fcntl.lockf(self._tmpfile, fcntl.LOCK_UN)
            if line_count == num_servers:
                break
            else:
                time.sleep(0.1)
        server_infos = [tuple([int(server_info_pattern.match(line).group(1)),
                               int(server_info_pattern.match(line).group(3))])
                        for line in self._tmpfile]
        server_infos = sorted(server_infos, key=lambda x: x[0])
        self._rpc_ports = [row[1] for row in server_infos]
        logger.debug("get_rpc_ports: ports (in MPI rank order): %s", self._rpc_ports)
        self._tmpfile.close()
        return self._rpc_ports[rank] 
开发者ID:NervanaSystems,项目名称:ngraph-python,代码行数:32,代码来源:mpilauncher.py


示例22: _trylock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def _trylock(lockfile):
        fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) 
开发者ID:harlowja,项目名称:fasteners,代码行数:4,代码来源:process_lock.py


示例23: _unlock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import lockf [as 别名]
def _unlock(lockfile):
        fcntl.lockf(lockfile, fcntl.LOCK_UN) 
开发者ID:harlowja,项目名称:fasteners,代码行数:4,代码来源:process_lock.py



注:本文中的fcntl.lockf方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。