Raise an EnvironmentError when the "guardfile" doesn't exist, or
        the process with the ID found in "pidfile" is still active.
435140
def guard(pidfile, guardfile=None):
    
    # Check guard
    if guardfile and not os.path.exists(guardfile):
        raise EnvironmentError("Guard file '%s' not found, won't start!" % guardfile)

    if os.path.exists(pidfile):
        running, pid = check_process(pidfile)
        if running:
            raise EnvironmentError("Daemon process #%d still running, won't start!" % pid)
        else:
            logging.getLogger("daemonize").info("Process #%d disappeared, continuing..." % pid)

    # Keep race condition window small, by immediately writing launcher process ID
    _write_pidfile(pidfile)
415789
def rmtree_or_file(path, ignore_errors=False, onerror=None):
  
  # TODO: Could add an rsync-based delete, as in
  # https://github.com/vivlabs/instaclone/blob/master/instaclone/instaclone.py#L127-L143
  if ignore_errors and not os.path.exists(path):
    return
  if os.path.isdir(path) and not os.path.islink(path):
    shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror)
  else:
    os.unlink(path)
1111101
def is_running(self):
        
        pid = self.get_pid()
        if pid is None:
            return False
        # The PID file may still exist even if the daemon isn't running,
        # for example if it has crashed.
        try:
            os.kill(pid, 0)
        except OSError as e:
            if e.errno == errno.ESRCH:
                # In this case the PID file shouldn't have existed in
                # the first place, so we remove it
                self.pid_file.release()
                return False
            # We may also get an exception if we're not allowed to use
            # kill on the process, but that means that the process does
            # exist, which is all we care about here.
        return True
87503
def ensure_file(path):
        
        try:
            exists = isfile(path)
            if not exists:
                with open(path, 'w+') as fname:
                    fname.write('initialized')
                return (True, path)
            return (True, 'exists')
        except OSError as e:  # pragma: no cover
            return (False, e)
1084120
def absent(name, user=None, signal=None):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': False,
           'comment': ''}

    if __opts__['test']:
        running = __salt__['ps.pgrep'](name, user=user)
        ret['result'] = None
        if running:
            ret['comment'] = ('{0} processes will '
                              'be killed').format(len(running))
        else:
            ret['comment'] = 'No matching processes running'
        return ret

    if signal:
        status = __salt__['ps.pkill'](name, user=user,
                                      signal=signal, full=True)
    else:
        status = __salt__['ps.pkill'](name, user=user, full=True)

    ret['result'] = True
    if status:
        ret['comment'] = 'Killed {0} processes'.format(len(status['killed']))
        ret['changes'] = status
    else:
        ret['comment'] = 'No matching processes running'
    return ret
1113404
def raise_os_error(_errno, path=None):
    

    msg = "%s: '%s'" % (strerror(_errno), path) if path else strerror(_errno)
    raise OSError(_errno, msg)
1195924
function ensureExists(path, mask, cb) {
    if (typeof mask == 'function') {
        cb = mask;
        mask = 0777;
    }

    filesystem.mkdir(path, mask, function(err) {
        if (err) {
            if (err.code == 'EEXIST') cb(null);
            else cb(err);
        } else cb(null);
    });
}
821372
def process_is_alive?(pid)
      begin
        Process.kill(0, pid)
        return true
      rescue Errno::ESRCH
        return false
      rescue SystemCallError => e
        return true
      end
    end
981674
def _check_pid(self, allow_reset=False):
        """"""
        if not self.pid == current_process().pid:
            if allow_reset:
                self.reset()
            else:
                raise RuntimeError("Forbidden operation in multiple processes")
472309
def pid(self):
        
        try:

            with open(self.pidfile, 'r') as pidfile:

                try:

                    pid = int(pidfile.read().strip())

                except ValueError:

                    return None

                try:

                    os.kill(pid, 0)

                except OSError as e:

                    if e.errno == errno.EPERM:

                        return pid

                    elif e.errno == errno.ESRCH:

                        return None

                    LOG.exception(
                        "os.kill returned unhandled error "
                        "{0}".format(e.strerror)
                    )
                    sys.exit(exit.PIDFILE_ERROR)

                return pid

        except IOError:

            if not os.path.isfile(self.pidfile):

                return None

            LOG.exception("Failed to read pidfile {0}.".format(self.pidfile))
            sys.exit(exit.PIDFILE_INACCESSIBLE)
317354
def ensure_dir_does_not_exist(*args):
    """"""
    path = os.path.join(*args)
    if os.path.isdir(path):
        shutil.rmtree(path)
956825
def cleanup(self):
        """"""
        try:
            os.remove(self.pid_file)
        except OSError as exc:
            logger.critical("Could not remove pid_file: %s", exc)

        # Save the final status of the flow.
        self.flow.pickle_dump()
748212
def lock_pid(self):
        
        
        if os.path.exists(self.lock_filename):
            return int(open(self.lock_filename).read())
        else:
            return None
668998
def _close_pidfile(self):
        """"""
        if self._pid_fd is not None:
            os.close(self._pid_fd)
        try:
            os.remove(self.pidfile)
        except OSError as ex:
            if ex.errno != errno.ENOENT:
                raise
1306975
def command_stop(self):
        '''
        
        '''
        if self.pidfile:
            if not os.path.exists(self.pidfile):
                sys.exit("Pidfile {!r} doesn't exist".format(self.pidfile))
            with open(self.pidfile) as pidfile:
                pid = int(pidfile.read())
            for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGKILL]:
                try:
                    if terminate(pid, sig, 3):
                        os.remove(self.pidfile)
                        # NOTE: we are not performing sys.exit here,
                        # otherwise restart command will not work
                        return
                except OSError as exc:
                    if exc.errno != errno.ESRCH:
                        raise
                    elif sig == signal.SIGINT:
                        sys.exit('Not running')
        sys.exit('No pidfile provided')
1303858
def start(self):
        
        # Check for a pidfile to see if the daemon already runs
        try:
            pf = file(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
            os.kill(pid, 0)
        except IOError:
            pid = None
        except OSError:
            pid = None

        if pid:
            message = "pidfile %s already exist. Daemon already running?\n"
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)

        # 
        self._daemonize()
974376
def kill(path):
    
    # try to read the pid from the pidfile
    pid = read(path)
    if pid is None:
        return

    # Try to kill the process.
    logging.info("Killing PID %s", pid)
    try:
        os.kill(pid, 9)
    except OSError as xxx_todo_changeme2:
        # re-raise if the error wasn't "No such process"
        (code, text) = xxx_todo_changeme2.args
        # re-raise if the error wasn't "No such process"
        if code != errno.ESRCH:
            raise