File based lock on ``path``.

    Creates a file based lock. When acquired, other processes or threads are
    prevented from acquiring the same lock until it is released.
168329
def lock_file(path):
    
    with _paths_lock:
        lock = _paths_to_locks.get(path)
        if lock is None:
            _paths_to_locks[path] = lock = _FileLock(path)
    return lock
878711
def create_lock(self, resource, **kwargs):
        
        lock = RedLock(resource=resource, created_by_factory=True, **kwargs)
        lock.redis_nodes = self.redis_nodes
        lock.quorum = self.quorum
        lock.factory = self
        return lock
237019
def create_lockfile(self):
        
        process = subprocess.Popen(
            self.pin_command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        stdout, stderr = process.communicate()
        if process.returncode == 0:
            self.fix_lockfile()
        else:
            logger.critical("ERROR executing %s", ' '.join(self.pin_command))
            logger.critical("Exit code: %s", process.returncode)
            logger.critical(stdout.decode('utf-8'))
            logger.critical(stderr.decode('utf-8'))
            raise RuntimeError("Failed to pip-compile {0}".format(self.infile))
674349
def write(path):
    
    pid = os.getpid()
    logging.info("Writing PID %s to '%s'", pid, path)
    try:
        pidfile = open(path, 'wb')
        # get a non-blocking exclusive lock
        fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        # clear out the file
        pidfile.seek(0)
        pidfile.truncate(0)
        # write the pid
        pidfile.write(str(pid))
    finally:
        try:
            pidfile.close()
        except:
            pass
441178
function ensureLock(client, path) {
  var lock = client.lock;
  if(!(lock && !('unlocked' in lock))) {
    // Create an error so we get a stack, too.
    var err = new Error('Attempted sync step without lock.');
    log.error({client: client, err: err}, 'Client should own lock but does not for ' + path);
    return false;
  }
  return true;
}
1315354
@Override
    public FileLock lock(long position, long size, boolean shared) throws IOException
    {
        return new FileLockImpl(this, position, size, shared);
    }
280946
public static void ensureDirectoryExists(final Path path) throws IOException {
        if (Files.exists(path)) {
            if (!Files.isDirectory(path)) {
                throw new IOException("path is not a directory: " + path);
            }
            // probably should fsync parent here just to be sure, but that might slow stuff down
        } else {
            Files.createDirectories(path);
            fsyncLineage(path.getParent());
        }
    }
163913
public static File ensureDir(String path, String name) throws IOException {
		if((path == null) || (path.length() == 0)) {
			throw new IOException("No configuration for (" + name + ")");
		}
		File dir = new File(path);
		if(dir.exists()) {
			if(!dir.isDirectory()) {
				throw new IOException("Dir(" + name + ") at (" + path + 
						") exists but is not a directory!");
			}
		} else {
			if(!dir.mkdirs()) {
				throw new IOException("Unable to create dir(" + name +") at ("
						+ path + ")");
			}
		}
		return dir;
	}
31473
FileLock acquireLock(File lockFile, FileChannel channel) {
        FileLock fileLock = null;
        try {
            fileLock = channel.tryLock();
            if (fileLock != null) {
                return fileLock;
            }
            throw new HazelcastException("Cannot acquire lock on " + lockFile.getAbsolutePath()
                    + ". File is already being used by another Hazelcast instance.");
        } catch (OverlappingFileLockException e) {
            throw new HazelcastException("Cannot acquire lock on " + lockFile.getAbsolutePath()
                    + ". File is already being used by this Hazelcast instance.", e);
        } catch (IOException e) {
            throw new HazelcastException("Unknown failure while acquiring lock on " + lockFile.getAbsolutePath(), e);
        } finally {
            if (fileLock == null) {
                closeResource(channel);
            }
        }
    }
227236
def lock(self, timeout=10):
        
        logger.debug("Locking %s", self.lock_file)
        if not os.path.exists(self.lock_file):
            self.ensure_path(self.lock_file)
            with open(self.lock_file, "w"):
                os.utime(self.lock_file)
        self._lock.acquire(timeout=timeout)
472833
private boolean processLockingMechanism() throws JournalException {
        boolean locked;
        if (lockRequestedFile.exists()) {
            try {
                if (!lockAcceptedFile.exists()) {
                    lockAcceptedFile.createNewFile();
                }
            } catch (IOException e) {
                throw new JournalException("Unable to create 'Lock Accepted' file at '"
                        + lockAcceptedFile.getPath() + "'");
            }
            locked = true;
        } else {
            if (lockAcceptedFile.exists()) {
                lockAcceptedFile.delete();
            }
            locked = false;
        }

        if (locked && !wasLocked) {
            recoveryLog.log("Lock request detected: "
                    + lockRequestedFile.getPath() + ", Lock accepted: "
                    + lockAcceptedFile.getPath());
        } else if (wasLocked && !locked) {
            recoveryLog.log("Lock request removed: "
                    + lockRequestedFile.getPath());
        }

        wasLocked = locked;
        return locked;
    }
231444
boolean tryLock(Path lockFile) throws JobLockException {
    log.debug("Attempting lock: {}", lockFile);
    try {
      return this.fs.createNewFile(lockFile);
    } catch (IOException e) {
      throw new JobLockException(e);
    }
  }
734624
def release_readlock(lockdir_name):
    
    # Make sure the lock still exists before deleting it
    if os.path.exists(lockdir_name) and os.path.isdir(lockdir_name):
        os.rmdir(lockdir_name)
1259349
def lock_pidfile_or_die(pidfile):
    
    pid = os.getpid()
    try:
        remove_if_stale_pidfile(pidfile)
        pid_write_file = pidfile + '.' + str(pid)
        fpid = open(pid_write_file, 'w')
        try:
            fpid.write("%s\n" % pid)
        finally:
            fpid.close()
        if not take_file_lock(pid_write_file, pidfile, "%s\n" % pid):
            sys.exit(1)
    except SystemExit:
        raise
    except Exception:
        log.exception("unable to take pidfile")
        sys.exit(1)
    return pid
22282
public static DirLock tryLock(FileSystem fs, Path dir) throws IOException {
    Path lockFile = getDirLockFile(dir);

    try {
      FSDataOutputStream ostream = HdfsUtils.tryCreateFile(fs, lockFile);
      if (ostream!=null) {
        LOG.debug("Thread ({}) Acquired lock on dir {}", threadInfo(), dir);
        ostream.close();
        return new DirLock(fs, lockFile);
      } else {
        LOG.debug("Thread ({}) cannot lock dir {} as its already locked.", threadInfo(), dir);
        return null;
      }
    } catch (IOException e) {
        LOG.error("Error when acquiring lock on dir " + dir, e);
        throw e;
    }
  }
579595
void lock(Path lockFile) throws JobLockException {
    log.debug("Creating lock: {}", lockFile);
    try {
      if (!this.fs.createNewFile(lockFile)) {
        throw new JobLockException("Failed to create lock file " + lockFile.getName());
      }
    } catch (IOException e) {
      throw new JobLockException(e);
    }
  }
575080
def lock_file(f, block=False):
    
    try:
        flags = fcntl.LOCK_EX
        if not block:
            flags |= fcntl.LOCK_NB
        fcntl.flock(f.fileno(), flags)
    except IOError as e:
        if e.errno in (errno.EACCES, errno.EAGAIN):
            raise SystemExit("ERROR: %s is locked by another process." %
                             f.name)
        raise