def unlock(f):
ret = fcntl.flock(_fd(f), fcntl.LOCK_UN)
return (ret == 0)
python类flock()的实例源码
def _lock_file(f, exclusive):
fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
def _unlock_file(f):
fcntl.flock(f, fcntl.LOCK_UN)
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 lock(f, flags):
ret = fcntl.flock(_fd(f), flags)
return (ret == 0)
def unlock(f):
ret = fcntl.flock(_fd(f), fcntl.LOCK_UN)
return (ret == 0)
def lock(file, flags):
fcntl.flock(file.fileno(), flags)
def unlock(file):
fcntl.flock(file.fileno(), fcntl.LOCK_UN)
def acquire(self):
fcntl.flock(self.handle, fcntl.LOCK_EX)
def release(self):
fcntl.flock(self.handle, fcntl.LOCK_UN)
def lock(f, flags):
ret = fcntl.flock(_fd(f), flags)
return (ret == 0)
def unlock(f):
ret = fcntl.flock(_fd(f), fcntl.LOCK_UN)
return (ret == 0)
def _lock_file(f, exclusive):
fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
def _unlock_file(f):
fcntl.flock(f, fcntl.LOCK_UN)
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}")
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
def release(self):
fcntl.flock(self._f, fcntl.LOCK_UN)
self._f.close()
# def scalar_summaries(prefix='', **kwargs):
# vs = [tf.Summary.Value(tag=prefix + '/' + name, simple_value=value) for name, value in kwargs.items()]
# s = tf.Summary(value=vs)
# return s
def __acquire(self):
max_lock = max_lock_seconds()
def timed_out():
logging.error("Lock timed out after {} seconds".format(max_lock))
# NOTE(CD):
#
# Bail and rely on the operating system to close the open lock
# file descriptor. They are closed on our behalf according to
# the POSIX standard. See https://linux.die.net/man/2/exit
#
# We emulate Ctrl-C instead of raising SystemExit via sys.exit()
# since exceptions are per-thread. SystemExit causes the
# interpreter to exit if unhandled. This is the only
# reliable way to trigger an exception in the main thread
# to make this testable. Open to improvements.
#
# The interpreter exits with status 1.
#
# See https://goo.gl/RXsXEs
_thread.interrupt_main()
self.timer = threading.Timer(max_lock, timed_out)
self.timer.start()
# acquire file lock
fcntl.flock(self.fd, fcntl.LOCK_EX)
def __release(self):
self.timer.cancel()
self.timer = None
fcntl.flock(self.fd, fcntl.LOCK_UN)
os.close(self.fd)