def lockfile(filename):
with open(filename, "wb") as opened:
fd = opened.fileno()
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as ioe:
if ioe.errno not in (errno.EACCES, errno.EAGAIN):
raise
yield False
else:
try:
yield True
finally:
fcntl.flock(fd, fcntl.LOCK_UN)
python类LOCK_EX的实例源码
def acquire(self):
try:
self._lock = open(self.lock_file, "w")
flock(self._lock, LOCK_EX | LOCK_NB)
logging.debug("Acquired exclusive lock on file: %s" % self.lock_file)
return self._lock
except Exception:
logging.debug("Error acquiring lock on file: %s" % self.lock_file)
if self._lock:
self._lock.close()
raise OperationError("Could not acquire lock on file: %s!" % self.lock_file)
def trylock(self):
fcntl.lockf(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
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
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
def _lock_file(f, exclusive):
fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
def latent_plan(init,goal,mode):
bits = np.concatenate((init,goal))
###### preprocessing ################################################################
## old code for caching...
lock = problem(network("lock"))
import fcntl
try:
with open(lock) as f:
print("lockfile found!")
fcntl.flock(f, fcntl.LOCK_SH)
except FileNotFoundError:
with open(lock,'wb') as f:
fcntl.flock(f, fcntl.LOCK_EX)
preprocess(bits)
###### do planning #############################################
sasp = problem(network("{}.sasp".format(action_type)))
plan_raw = problem(network("{}.sasp.plan".format(action_type)))
plan = problem(network("{}.{}.plan".format(action_type,mode)))
echodo(["planner-scripts/limit.sh","-v", "-o",options[mode], "--","fd-sas-clean", sasp])
assert os.path.exists(plan_raw)
echodo(["mv",plan_raw,plan])
out = echo_out(["lisp/parse-plan.bin",plan, *list(init.astype('str'))])
lines = out.splitlines()
return np.array([ [ int(s) for s in l.split() ] for l in lines ])
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
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
def __init__(self, fd, keys, excl=True, lock=False, mod=1048573, _ctx_cleanup=None):
self.fd = fd
self.locked = False
self.mode = fcntl.LOCK_EX if excl else fcntl.LOCK_SH
self._ctx_cleanup = _ctx_cleanup
# sort so locks are acquired in consistent order
# guarantees no inter-process deadlocks
locks = set(hash(key) % mod for key in keys)
self.locks = tuple(sorted(locks))
if lock:
self.lock()
def exclusive(self, *keys):
self._update(fcntl.LOCK_EX)
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
项目源码
文件源码
阅读 19
收藏 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 _trylock(lockfile):
fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
def __init__(self, filename, mode='rb'):
self.filename = filename
self.mode = mode
self.file = None
if 'r' in mode:
self.file = open_file(filename, mode)
lock(self.file, LOCK_SH)
elif 'w' in mode or 'a' in mode:
self.file = open_file(filename, mode.replace('w', 'a'))
lock(self.file, LOCK_EX)
if 'a' not in mode:
self.file.seek(0)
self.file.truncate(0)
else:
raise RuntimeError("invalid LockedFile(...,mode)")
def acquire(self):
fcntl.flock(self.handle, fcntl.LOCK_EX)
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 _lock_file(f, exclusive):
fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)