If file is locked then terminate program else lock file.
435680
def assert_lock(fname):
    

    if not set_lock(fname):
        logger.error('File {} is already locked. Terminating.'.format(fname))
        sys.exit()
905628
public void lock() throws FileLockException, IOException {
        if (mode == AccessMode.READ_ONLY) {
            return;
        }

        for (int retries = 0; retries < max_retries_connect; retries++) {
            try {
                fileLock = channel.lock();
                break; // the lock was succesful
            } catch (OverlappingFileLockException e) {
                try {
                    logger.debug("Can't open file '" + osFile.getAbsolutePath()
                            + "' because it's locked. Waiting {} ms and retry {}", RETRY_CONNECT_WAITTIME,
                            retries);
                    System.runFinalization(); // FORCE FINALIZATION TO COLLECT ALL THE PENDING BUFFERS
                    Thread.sleep(RETRY_CONNECT_WAITTIME);
                } catch (InterruptedException ex) {
                    // will throw a FileLockException further
                }
            }
        }

        if (fileLock == null) {
            this.close();
            throw new FileLockException("File " + osFile.getPath()
                    + " is locked by another process, maybe the database is in use by another process.");
        }
    }
914196
public function lock()
    {
        if (!$this->isLocked()) {
            $file = fopen($this->getFilePath(), 'w');
            if ($file) {
                fwrite($file, getmypid());
                fclose($file);
                return true;
            }
        }
        return false;
    }
1112449
public void unlock() throws IOException {
        System.runFinalization();
        if (fileLock != null) {
            try {
                fileLock.release();
            } catch (ClosedChannelException e) {
                throw new IOException("Can't close Channel in " + osFile + ".");
            }
            fileLock = null;
        }
    }
1117472
def release(self):
        """"""
        if not self.acquired:
            raise threading.ThreadError("Unable to release an unacquired"
                                        " lock")
        try:
            self.unlock()
        except IOError:
            self.logger.exception("Could not unlock the acquired lock opened"
                                  " on `%s`", self.path)
        else:
            self.acquired = False
            try:
                self._do_close()
            except IOError:
                self.logger.exception("Could not close the file handle"
                                      " opened on `%s`", self.path)
            else:
                self.logger.log(_utils.BLATHER,
                                "Unlocked and closed file lock open on"
                                " `%s`", self.path)
902256
public void lockBlocks(long fileId, List<Long> blockIds) throws IOException {
    Map<Long, Long> blockIdToLockId = new HashMap<>();
    List<Throwable> errors = new ArrayList<>();
    synchronized (mLock) {
      if (mPersistingInProgressFiles.containsKey(fileId)) {
        throw new IOException("the file " + fileId + " is already being persisted");
      }
    }
    try {
      // lock all the blocks to prevent any eviction
      for (long blockId : blockIds) {
        long lockId = mBlockWorker.lockBlock(Sessions.CHECKPOINT_SESSION_ID, blockId);
        blockIdToLockId.put(blockId, lockId);
      }
    } catch (BlockDoesNotExistException e) {
      errors.add(e);
      // make sure all the locks are released
      for (long lockId : blockIdToLockId.values()) {
        try {
          mBlockWorker.unlockBlock(lockId);
        } catch (BlockDoesNotExistException bdnee) {
          errors.add(bdnee);
        }
      }

      if (!errors.isEmpty()) {
        StringBuilder errorStr = new StringBuilder();
        errorStr.append("failed to lock all blocks of file ").append(fileId).append("\n");
        for (Throwable error : errors) {
          errorStr.append(error).append('\n');
        }
        throw new IOException(errorStr.toString());
      }
    }
    synchronized (mLock) {
      mPersistingInProgressFiles.put(fileId, blockIdToLockId);
    }
  }
1128193
private static void lockBoth(Lock sourceWriteLock, Lock destWriteLock) {
    while (true) {
      sourceWriteLock.lock();
      if (destWriteLock.tryLock()) {
        return;
      } else {
        sourceWriteLock.unlock();
      }

      destWriteLock.lock();
      if (sourceWriteLock.tryLock()) {
        return;
      } else {
        destWriteLock.unlock();
      }
    }
  }
372515
def raise_or_lock(self, key, timeout):
        
        lock_path = self._get_lock_path(key)
        try:
            # Create lock file, raise exception if it exists
            fd = os.open(lock_path, os.O_CREAT | os.O_EXCL)
        except OSError as error:
            if error.errno == errno.EEXIST:
                # File already exists, check its modification time
                mtime = os.path.getmtime(lock_path)
                ttl = mtime + timeout - time.time()
                if ttl > 0:
                    raise AlreadyQueued(ttl)
                else:
                    # Update modification time if timeout happens
                    os.utime(lock_path, None)
                    return
            else:
                # Re-raise unexpected OSError
                raise
        else:
            os.close(fd)
1298351
public synchronized void close() throws SecurityException {
        super.close();
        // Unlock any lock file.
        if (lockFileName == null) {
            return;
        }
        try {
            // Closing the lock file's FileOutputStream will close
            // the underlying channel and free any locks.
            lockStream.close();
        } catch (Exception ex) {
            // Problems closing the stream.  Punt.
        }
        synchronized(locks) {
            locks.remove(lockFileName);
        }
        new File(lockFileName).delete();
        lockFileName = null;
        lockStream = null;
    }
1334995
def lock_file(filename, interval=.5, timeout=15):
    '''
    
    '''
    log.trace('Attempting to obtain lock for %s', filename)
    lock = filename + '.lock'
    start = time.time()
    while True:
        if os.path.exists(lock):
            if time.time() - start >= timeout:
                log.warning('Unable to obtain lock for %s', filename)
                return False
            time.sleep(interval)
        else:
            break

    with salt.utils.files.fopen(lock, 'a'):
        pass
4428
public void lock() throws H2DBLockException {
        try {
            final File dir = settings.getDataDirectory();
            lockFile = new File(dir, "odc.update.lock");
            checkState();
            int ctr = 0;
            do {
                try {
                    if (!lockFile.exists() && lockFile.createNewFile()) {
                        file = new RandomAccessFile(lockFile, "rw");
                        lock = file.getChannel().lock();
                        file.writeBytes(magic);
                        file.getChannel().force(true);
                        Thread.sleep(20);
                        file.seek(0);
                        final String current = file.readLine();
                        if (current != null && !current.equals(magic)) {
                            lock.close();
                            lock = null;
                            LOGGER.debug("Another process obtained a lock first ({})", Thread.currentThread().getName());
                        } else {
                            addShutdownHook();
                            final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                            LOGGER.debug("Lock file created ({}) {} @ {}", Thread.currentThread().getName(), magic, timestamp.toString());
                        }
                    }
                } catch (IOException | InterruptedException ex) {
                    LOGGER.trace("Expected error as another thread has likely locked the file", ex);
                } finally {
                    if (lock == null && file != null) {
                        try {
                            file.close();
                            file = null;
                        } catch (IOException ex) {
                            LOGGER.trace("Unable to close the lock file", ex);
                        }
                    }
                }
                if (lock == null || !lock.isValid()) {
                    try {
                        final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                        LOGGER.debug("Sleeping thread {} ({}) for {} seconds because an exclusive lock on the database could not be obtained ({})",
                                Thread.currentThread().getName(), magic, SLEEP_DURATION / 1000, timestamp.toString());
                        Thread.sleep(SLEEP_DURATION);
                    } catch (InterruptedException ex) {
                        LOGGER.debug("sleep was interrupted.", ex);
                        Thread.currentThread().interrupt();
                    }
                }
            } while (++ctr < MAX_SLEEP_COUNT && (lock == null || !lock.isValid()));
            if (lock == null || !lock.isValid()) {
                throw new H2DBLockException("Unable to obtain the update lock, skipping the database update. Skippinig the database update.");
            }
        } catch (IOException ex) {
            throw new H2DBLockException(ex.getMessage(), ex);
        }
    }
877323
def stop(self):
        """"""
        with self.lock:
            self._message_received(ConnectionClosed(self._file, self))
793184
def lock(self):
        '''
        
        '''

        # Open file
        self.__fd = open(self.__lockfile, "w")

        # Get it locked
        if self.__locktype == "wait":
            # Try to get it locked until ready
            fcntl.flock(self.__fd.fileno(), fcntl.LOCK_EX)
        elif self.__locktype == "lock":
            # Try to get the locker if can not raise an exception
            try:
                fcntl.flock(self.__fd.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
            except IOError:
                raise AlreadyLocked("File is already locked")
1001857
private void lockSourceAndCopy(File sourceFile, File copyFile) {
    sourceFile.opened();
    ReadWriteLock sourceLock = sourceFile.contentLock();
    if (sourceLock != null) {
      sourceLock.readLock().lock();
    }
    ReadWriteLock copyLock = copyFile.contentLock();
    if (copyLock != null) {
      copyLock.writeLock().lock();
    }
  }
1307936
def _simple_lock(f):
    
    lock_file = f + ".lock"
    timeout = 20
    curtime = 0
    interval = 2
    while os.path.exists(lock_file):
        time.sleep(interval)
        curtime += interval
        if curtime > timeout:
            os.remove(lock_file)
    with open(lock_file, "w") as out_handle:
        out_handle.write("locked")
    yield
    if os.path.exists(lock_file):
        os.remove(lock_file)
46346
def Unlock(fd, path):
  
  try:
    fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB)
  except IOError as e:
    if e.errno == errno.EWOULDBLOCK:
      raise IOError('Exception unlocking %s. Locked by another process.' % path)
    else:
      raise IOError('Exception unlocking %s. %s.' % (path, str(e)))
1129434
def release(self):
        """"""
        if self.lock_filename != self.pid_filename:
            try:
                os.unlink(self.lock_filename)
            except OSError:
                pass

        try:
            os.remove(self.pid_filename)
        except OSError:
            pass