当前位置: 首页>>代码示例>>Python>>正文


Python fcntl.flock方法代码示例

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


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

示例1: run

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def run(self):
		"check mysql replication and handle errors"

		global sigint_up

		# add file lock first to sure only 1 process is running on this instance
		if not os.path.exists(self.lockfile):
			os.system("touch %s" %(self.lockfile))

		f = open(self.lockfile, "r")

		try:
			fcntl.flock(f.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
			self.logger.debug("get file lock on %s success" %(self.lockfile))
		except Exception, e:
			msg = "can't get lock for mysql %s, please check script is already running" %(self.port)
			self.logger.error(msg)
			sigint_up = True
			raise Exception(msg) 
开发者ID:dumingyou,项目名称:mysql_repl_repair,代码行数:21,代码来源:mysql_repl_repair2.py

示例2: run

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def run(self):
		"check mysql replication and handle errors"

		global sigint_up

		# add file lock first to sure only 1 process is running on this instance
		if not os.path.exists(self.lockfile):
			os.system("touch %s" %(self.lockfile))

		f = open(self.lockfile, "r")

		try:
			fcntl.flock(f.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
			self.logger.debug("get file lock on %s success" %(self.lockfile))
		except Exception, e:
			msg = "can't get lock for mysql %s, please check script is already running" %(self.port)
			self.logger.error(msg)
			sigint_up = True
			raise Exception(msg)

		# check binlog format 
开发者ID:dumingyou,项目名称:mysql_repl_repair,代码行数:23,代码来源:mysql_repl_repair.py

示例3: __enter__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def __enter__(self):
      self._fo = open(self._filename, self._mode)

      # Regardless of opening mode we always seek to the beginning of file.
      # This simplifies code working with LockedFile and also ensures that
      # we lock (and unlock below) always the same region in file on win32.
      self._fo.seek(0)

      try:
        if sys.platform == 'win32':
          # We are locking here fixed location in file to use it as
          # an exclusive lock on entire file.
          msvcrt.locking(self._fo.fileno(), msvcrt.LK_LOCK, 1)
        else:
          fcntl.flock(self._fo.fileno(), fcntl.LOCK_EX)
      except IOError:
        self._fo.close()
        raise

      return self._fo 
开发者ID:google,项目名称:gtest-parallel,代码行数:22,代码来源:gtest_parallel.py

示例4: __exit__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def __exit__(self, exc_type, exc_value, traceback):
      # Flush any buffered data to disk. This is needed to prevent race
      # condition which happens from the moment of releasing file lock
      # till closing the file.
      self._fo.flush()

      try:
        if sys.platform == 'win32':
          self._fo.seek(0)
          msvcrt.locking(self._fo.fileno(), msvcrt.LK_UNLCK, 1)
        else:
          fcntl.flock(self._fo.fileno(), fcntl.LOCK_UN)
      finally:
        self._fo.close()

      return exc_value is None 
开发者ID:google,项目名称:gtest-parallel,代码行数:18,代码来源:gtest_parallel.py

示例5: lock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def lock(self):
        if self.handle is None or self.handle.closed:
            self.handle = open(self.path, "w+")
            self.fd = self.handle.fileno()
        if (self.flags & fcntl.LOCK_NB) != 0 or self.seconds is None:
            try:
                fcntl.flock(self.handle, self.flags)
            except IOError as e:
                if e.errno not in [errno.EACCES, errno.EAGAIN]:
                    raise e
                raise Locked(self.path)
        else:
            with timeout(self.seconds):
                try:
                    fcntl.flock(self.handle, self.flags)
                except IOError as e:
                    errnos = [errno.EINTR, errno.EACCES, errno.EAGAIN]
                    if e.errno not in errnos:
                        raise e
                    raise Timeout(self.path) 
开发者ID:mesosphere-backup,项目名称:deimos,代码行数:22,代码来源:flock.py

示例6: lock_browser

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def lock_browser(directory):
    bash = """
        set -o errexit -o nounset -o pipefail

        function files_by_inode {
          find "$1" -type f -printf '%i %p\\n' | LC_ALL=C LANG=C sort
        }

        function locking_pids_by_inode {
          cat /proc/locks |
          sed -r '
            s/^.+ ([^ ]+) +([0-9]+) [^ :]+:[^ :]+:([0-9]+) .+$/\\3 \\2 \\1/
          ' | LC_ALL=C LANG=C sort
        }

        join <(locking_pids_by_inode) <(files_by_inode "$1")
    """
    subprocess.check_call(["bash", "-c", bash, "bash",
                           os.path.abspath(directory)])

# Thanks to Glenn Maynard
# http://stackoverflow.com/questions/5255220/fcntl-flock-how-to-implement-a-timeout/5255473#5255473 
开发者ID:mesosphere-backup,项目名称:deimos,代码行数:24,代码来源:flock.py

示例7: udpate_status

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def udpate_status(status_file_path, module_data, module):
	lock_file_path = "{}.lock".format(status_file_path)
	while True:
		status_file_lock = open(lock_file_path, 'r')
		try:
			fcntl.flock(status_file_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
			with open(status_file_path, "r+") as status_file:
				data = json.load(status_file)
				status_file.seek(0)
				data[module].update(module_data)
				json.dump(data, status_file)
			fcntl.flock(status_file_lock, fcntl.LOCK_UN)
			return
		except:
			time.sleep(0.1)
		status_file_lock.close() 
开发者ID:BishopFox,项目名称:IDontSpeakSSL,代码行数:18,代码来源:utils.py

示例8: _create_pid_file

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def _create_pid_file():
    global fp
    pidfile = CONF.etc.pidfile
    if pidfile is None:
        raise UpdaterErr("No pidfile option found in config file.")
    try:
        fp = open(pidfile, 'w')
        # LOCK_EX    /* exclusive lock */
        # LOCK_NB   * don't block when locking */
        fcntl.flock(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
        fp.truncate()
        pid = os.getpid()
        fp.write(str(pid))
        fp.flush()
    except Exception as e:
        raise UpdaterErr("Failed to lock pidfile, perhaps named_updater is already running.") 
开发者ID:qunarcorp,项目名称:open_dnsdb,代码行数:18,代码来源:updater.py

示例9: _acquire

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def _acquire(self, wait, wrflag, lockflag):
        wrflag |= os.O_CREAT
        fileno = os.open(self.filename, wrflag)
        try:
            if not wait:
                lockflag |= self._module.LOCK_NB
            self._module.flock(fileno, lockflag)
        except IOError:
            os.close(fileno)
            if not wait:
                # this is typically
                # "[Errno 35] Resource temporarily unavailable",
                # because of LOCK_NB
                return False
            else:
                raise
        else:
            self._filedescriptor.fileno = fileno
            return True 
开发者ID:sqlalchemy,项目名称:dogpile.cache,代码行数:21,代码来源:file.py

示例10: ExecFlock

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def ExecFlock(self, lockfile, *cmd_list):
    """
    Emulates the most basic behavior of Linux's flock(1).

    Rely on exception handling to report errors.
    Note that the stock python on SunOS has a bug where fcntl.flock(fd, LOCK_EX) always fails with EBADF,
    that's why we use this F_SETLK hack instead.
    """
    # noinspection PyUnresolvedReferences
    fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0o666)
    if sys.platform.startswith('aix'):
      # Python on AIX is compiled with LARGEFILE support, which changes the
      # struct size.
      op = struct.pack('hhIllqq', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
    else:
      op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
    fcntl.fcntl(fd, fcntl.F_SETLK, op)
    return subprocess.call(cmd_list) 
开发者ID:refack,项目名称:GYP3,代码行数:20,代码来源:flock_tool.py

示例11: __enter__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def __enter__(self):
        if self.path is None:
            return self.pidfile

        self.pidfile = open(self.path, "a+")
        try:
            fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError:
            self.pidfile = None
            raise SystemExit("Already running according to " + self.path)
        self.pidfile.seek(0)
        self.pidfile.truncate()
        self.pidfile.write(str(os.getpid()))
        self.pidfile.flush()
        self.pidfile.seek(0)
        return self.pidfile 
开发者ID:perfsonar,项目名称:pscheduler,代码行数:18,代码来源:pidfile.py

示例12: write_pidfile

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def write_pidfile(pid, pidfile):
    """
    This method writes the PID to the pidfile and locks it while the process is running.

    :param pid: PID of SmartHomeNG
    :param pidfile: Name of the pidfile to write to
    :type pid: int
    :type pidfile: str
    """

    fd = open(pidfile, 'w+')
    fd.write("%s" % pid)
    fd.close()

    # lock pidfile:
    try:
        fd = os.open(pidfile, os.O_RDONLY)
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        # don't close fd or lock is gone
    except OSError as e:
        print("Could not lock pid file: %d (%s)" % (e.errno, e.strerror) , file=sys.stderr) 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:23,代码来源:daemon.py

示例13: acquire

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def acquire(self, blocking=None):
        # Give an opportunity to set blocking with the class for context use
        if blocking is None:
            blocking = self.blocking

        if blocking:
            lock_mode = fcntl.LOCK_EX
        else:
            lock_mode = fcntl.LOCK_EX | fcntl.LOCK_NB
        if self.lock_file.closed:
            self._get_lock_file_handle()
        if not self.locked:
            try:
                self.lock = fcntl.flock(self.lock_file, lock_mode)
                self.locked = True
            except IOError:
                raise IOError("File '{}' is already locked.".format(self.lock_file_name))
        else:
            raise IOError("File '{}' is already locked.".format(self.lock_file_name)) 
开发者ID:Tufin,项目名称:pytos,代码行数:21,代码来源:utils.py

示例14: __exit__

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def __exit__(self, exc_type, exc_val, traceback):
        if (exc_type is None and self._data_written):
            os.replace(self._temp_file_path, self._config_file)
            os.chmod(self._config_file, 0o660)
            shutil.chown(self._config_file, user=USER, group=GROUP)
        else:
            self._temp_file.close()
            os.unlink(self._temp_file_path)
            if (self._Log):
                self._Log.error(f'configuration manager exiting with error: {exc_val}')

        # releasing lock for purposes specified in flock(1) man page under -u (unlock)
        fcntl.flock(self._config_lock, fcntl.LOCK_UN)
        self._config_lock.close()
        if (self._Log):
            self._Log.debug(f'file lock released for {self._file_name}')

        if (exc_type is not ValidationError):
            return True

    #will load json data from file, convert it to a python dict, then returned as object 
开发者ID:DOWRIGHTTV,项目名称:dnxfirewall-cmd,代码行数:23,代码来源:dnx_file_operations.py

示例15: write_hosts

# 需要导入模块: import fcntl [as 别名]
# 或者: from fcntl import flock [as 别名]
def write_hosts(self, host_map, name):
        tag = 'vpn-slice-{} AUTOCREATED'.format(name)
        with open(self.path, 'r+') as hostf:
            fcntl.flock(hostf, fcntl.LOCK_EX)  # POSIX only, obviously
            lines = hostf.readlines()
            keeplines = [l for l in lines if not l.endswith('# %s\n' % tag)]
            hostf.seek(0, 0)
            hostf.writelines(keeplines)
            for ip, names in host_map:
                print('%s %s\t\t# %s' % (ip, ' '.join(names), tag), file=hostf)
            hostf.truncate()
        return len(host_map) or len(lines) - len(keeplines) 
开发者ID:dlenski,项目名称:vpn-slice,代码行数:14,代码来源:posix.py


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