python类LOCK_NB的实例源码

test.py 文件源码 项目:contrail-ansible-internal 作者: Juniper 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def __init__(self):
        self.fh = None
        self.is_running = False
        try:
            self.fh = open(LOCK_PATH, 'w')
            fcntl.lockf(self.fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except EnvironmentError as err:
            if self.fh is not None:
                self.is_running = True
            else:
                raise
daemon.py 文件源码 项目:shadowsocksr 作者: shadowsocksr-backup 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
helper.py 文件源码 项目:zeronet-debian 作者: bashrc 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def openLocked(path, mode="w"):
    if os.name == "posix":
        import fcntl
        f = open(path, mode)
        fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
    else:
        f = open(path, mode)
    return f
daemon.py 文件源码 项目:ShadowSocks 作者: immqy 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
pc.py 文件源码 项目:weibo 作者: windskyer 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def write_pid_file(pid_file, pid):
    try:
        fd = os.open(pid_file, os.O_RDWR | os.O_CREAT,
                     stat.S_IRUSR | stat.S_IWUSR)
    except OSError as e:
        LOG.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' % utils.to_str(r))
        else:
            logging.error('already started')
        os.close(fd)
        return -1
    os.ftruncate(fd, 0)
    os.write(fd, utils.to_bytes(str(pid)))
    return 0
process_lock.py 文件源码 项目:deb-python-fasteners 作者: openstack 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def _trylock(lockfile):
        fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
plock.py 文件源码 项目:aquests 作者: hansroh 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def __init__(self, filename):
            self.filename = filename
            # This will create it if it does not exist already
            self.handle = open(filename, 'w')

        # Bitwise OR fcntl.LOCK_NB if you need a non-blocking lock
lock.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def _try_lock(self, fd):
        """Try to acquire the lock file without blocking.

        :param int fd: file descriptor of the opened file to lock

        """
        try:
            fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError as err:
            if err.errno in (errno.EACCES, errno.EAGAIN):
                logger.debug(
                    "A lock on %s is held by another process.", self._path)
                raise errors.LockError(
                    "Another instance of Certbot is already running.")
            raise
experiment.py 文件源码 项目:chi 作者: rmst 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def run_chiboard(self):
    pass
    import subprocess
    from chi import board
    from chi.board import CHIBOARD_HOME, MAGIC_PORT

    port = None
    start = False
    cbc = join(CHIBOARD_HOME, CONFIG_NAME)
    if os.path.isfile(cbc):
      with open(cbc) as f:
        import fcntl
        try:
          fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
          start = True
          fcntl.flock(f, fcntl.LOCK_UN)
        except (BlockingIOError, OSError):  # chiboard is running
          try:
            data = json.load(f)
            port = data.get('port')
          except json.JSONDecodeError:
            port = None

    else:
      start = True

    if start:
      from chi.board import main
      chiboard = main.__file__
      subprocess.check_call([sys.executable, chiboard, '--port', str(MAGIC_PORT), '--daemon'])
      port = MAGIC_PORT

    if port is None:
      logger.warning('chiboard seems to be running but port could not be read from its config')
    else:
      logger.info(f"{self.f.__name__} started. Check progress at http://localhost:{port}/exp/#/local{self.logdir}")
util.py 文件源码 项目:chi 作者: rmst 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self, path):
    import json
    self._path = path
    try:
      with open(path) as f:
        old_data = json.load(f)
    except json.JSONDecodeError:
      logger.warning('Could not decode config')
      old_data = {}
    except OSError:
      logger.debug('No config file')
      old_data = {}

    for i in range(10):
      try:
        self._f = open(path, 'w+')
        fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
        self._locked = True
        break
      except BlockingIOError:
        import signal
        pid = old_data.get('pid')
        if pid:
          logger.info(f'Config file is locked (try {i}). Killing previous instance {pid}')
          os.kill(pid, signal.SIGTERM)
          time.sleep(.05)
        else:
          logger.error(f'Config file is locked and no pid to kill')
    assert self._locked
util.py 文件源码 项目:Houston 作者: squaresLab 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def lock_file(fname):
    """Lock a file."""
    import fcntl
    f = open(fname, mode='w')
    try:
        fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except Exception:
        return None
    return f
helpers.py 文件源码 项目:appetite 作者: Bridgewater 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __enter__(self):
        """Enter RunSingleInstance class
        :return: self
        """
        self.__checked = True

        try:
            self.__filelock = open(self.__lockfile, 'w+')
            # None blocking lock
            fcntl.lockf(self.__filelock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError:
            if self.__filelock is not None:
                self.__is_running = True
        return self
synchronization.py 文件源码 项目:MCSManager-fsmodule 作者: Suwings 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def do_acquire_read_lock(self, wait):
        filedescriptor = self._open(os.O_CREAT | os.O_RDONLY)
        if not wait:
            try:
                fcntl.flock(filedescriptor, fcntl.LOCK_SH | fcntl.LOCK_NB)
                return True
            except IOError:
                os.close(filedescriptor)
                self._filedescriptor.remove()
                return False
        else:
            fcntl.flock(filedescriptor, fcntl.LOCK_SH)
            return True
synchronization.py 文件源码 项目:MCSManager-fsmodule 作者: Suwings 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def do_acquire_write_lock(self, wait):
        filedescriptor = self._open(os.O_CREAT | os.O_WRONLY)
        if not wait:
            try:
                fcntl.flock(filedescriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
                return True
            except IOError:
                os.close(filedescriptor)
                self._filedescriptor.remove()
                return False
        else:
            fcntl.flock(filedescriptor, fcntl.LOCK_EX)
            return True
utils.py 文件源码 项目:django-botmanager 作者: dimoha 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def management_lock(view_func):

    def wrapper_lock(*args, **kwargs):
        try:
            lock_file_path = os.path.join('/tmp/', "{0}.lock".format(args[0].__class__.__module__.split('.')[-1]))
            f = open(lock_file_path, 'w')
            fcntl.lockf(f, fcntl.LOCK_EX + fcntl.LOCK_NB)
        except IOError:
            logging.debug("Process already is running.")
            os._exit(1)
        return view_func(*args, **kwargs)

    wrapper_lock.view_func = view_func.view_func if hasattr(view_func, 'view_func') else view_func
    return wrapper_lock
filelock.py 文件源码 项目:PY-Snip 作者: MrKiven 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def trylock(fd):
    import fcntl
    import errno
    try:
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError, e:
        if e.errno in (errno.EACCES, errno.EAGAIN):
            return False
        else:
            raise
    return True
ftdi.py 文件源码 项目:bch-firmware-tool 作者: bigclownlabs 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _lock(self):
        if not fcntl or not self.ser:
            return
        fcntl.flock(self.ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        logging.debug('_lock')
iptables_raw.py 文件源码 项目:dcos-ansible-packet 作者: ContainerSolutions 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def acquire_lock_or_exit(self, wait_for_seconds=10):
        lock_file = self.STATE_DIR + '/.iptables.lock'
        i = 0
        f = open(lock_file, 'w+')
        while i < wait_for_seconds:
            try:
                fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
                return
            except IOError:
                i += 1
                time.sleep(1)
        Iptables.module.fail_json(msg="Could not acquire lock to continue execution! "
                                      "Probably another instance of this module is running.")

    # Check if a table has anything to flush (to check all tables pass table='*').
utils.py 文件源码 项目:isar 作者: ilbers 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def unlockfile(lf):
    """
    Unlock a file locked using lockfile()
    """
    try:
        # If we had a shared lock, we need to promote to exclusive before
        # removing the lockfile. Attempt this, ignore failures.
        fcntl.flock(lf.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
        os.unlink(lf.name)
    except (IOError, OSError):
        pass
    fcntl.flock(lf.fileno(), fcntl.LOCK_UN)
    lf.close()
shellutils.py 文件源码 项目:isar 作者: ilbers 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def unlockfile(lock_file):
    """
    Unlock a file locked using lockfile()
    """
    try:
        # If we had a shared lock, we need to promote to exclusive before
        # removing the lockfile. Attempt this, ignore failures.
        fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
        os.unlink(lock_file.name)
    except (IOError, OSError):
        pass
    fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
    lock_file.close()

#ENDOFCOPY


问题


面经


文章

微信
公众号

扫码关注公众号