def _update(self, mode):
if mode is None:
if self.locked:
fcntl.lockf(self.fd, fcntl.LOCK_UN)
self.locked = False
elif self.mode is not mode or not self.locked:
self.mode = mode
self.locked = True
for offset in self.locks:
fcntl.lockf(self.fd, self.mode, 1, offset)
python类lockf()的实例源码
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
pid_control.py 文件源码
项目:lustre_task_driven_monitoring_framework
作者: GSI-HPC
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def create_pid_file(self):
fd = open(self._pid_file, 'wb')
fcntl.lockf(fd, fcntl.LOCK_EX)
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
fd.write(self._pid + ";" + timestamp)
fd.close()
return True
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()
def _trylock(lockfile):
fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
def _unlock(lockfile):
fcntl.lockf(lockfile, fcntl.LOCK_UN)
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
def run(self):
"""
THIS IS BLOCKING! CALL IT AT LAST!
"""
with open(Job.lockFileName, 'w') as f:
rv = fcntl.lockf(f.fileno(), fcntl.LOCK_EX)
print("job {} is running.".format(os.getpid()))
f.write(str(os.getpid()) + '\n')
f.flush()
self.action()
fcntl.lockf(f.fileno(), fcntl.LOCK_UN)
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
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]
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
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
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
def __exit__(self, type, value, tb): # pylint: disable=redefined-builtin
"""Exit RunSingleInstance class
:return: None
"""
try:
if not self.__is_running:
fcntl.lockf(self.__filelock, fcntl.LOCK_UN)
self.__filelock.close()
os.unlink(self.__lockfile)
except Exception as err:
logger.error("Error unlocking single instance file", error=err.message)
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
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
def __init__(self, hid):
self.file = open(hid, 'rb+', buffering=0)
fcntl.lockf(self.file, fcntl.LOCK_EX)
flag = fcntl.fcntl(self.file, fcntl.F_GETFL)
fcntl.fcntl(self.file, fcntl.F_SETFL, flag | os.O_NONBLOCK)
# Clock 48 MHz
fcntl.ioctl(self.file, 0xC0054806, bytes([0xA1, 0x01, 0x02]))
# No flow control mode
fcntl.ioctl(self.file, 0xC0054806, bytes([0xA1, 0x03, 0x04]))
self.gpio = [0x00, 0x00]
self.read_buffer = []
self._write_gpio()
def connection_lock(self):
f = self._play_context.connection_lockfd
display.vvvv('CONNECTION: pid %d waiting for lock on %d' % (os.getpid(), f), host=self._play_context.remote_addr)
fcntl.lockf(f, fcntl.LOCK_EX)
display.vvvv('CONNECTION: pid %d acquired lock on %d' % (os.getpid(), f), host=self._play_context.remote_addr)
def connection_unlock(self):
f = self._play_context.connection_lockfd
fcntl.lockf(f, fcntl.LOCK_UN)
display.vvvv('CONNECTION: pid %d released lock on %d' % (os.getpid(), f), host=self._play_context.remote_addr)
def __enter__(self):
# Lock the database interface (multi-threading)
self._thread_lock.acquire()
# Lock the database (multi-processing)
fcntl.lockf(self._db_fd, fcntl.LOCK_EX)