Atomically writes the pidfile.
 NB: This throws exceptions if the pidfile contains the pid of another running process.

 +create_parents+  If true, all parts of the path up to the file's dirname will be created.
977452
def write(create_parents=true)
      FileUtils.mkdir_p(File.dirname(@pid_file)) if create_parents

      # Protip from Wilson: binary mode keeps things sane under Windows
      # Closing the fd releases our lock
      File.open(@pid_file, 'a+b', 0644) do |f|
        f.flock(File::LOCK_EX)

        # Check if process is already running
        pid = f.read().strip().to_i()
        if pid == Process.pid()
          return
        elsif VCAP.process_running?(pid)
          raise ProcessRunningError.new("Process already running (pid=%d)." % (pid))
        end

        # We're good to go, write our pid
        f.truncate(0)
        f.rewind()
        f.write("%d\n" % (Process.pid()))
        f.flush()
      end
    end
1234535
def _begin_write(session: UpdateSession,
                 loop: asyncio.AbstractEventLoop,
                 rootfs_file_path: str):
    
    session.set_progress(0)
    session.set_stage(Stages.WRITING)
    write_future = asyncio.ensure_future(loop.run_in_executor(
        None, file_actions.write_update, rootfs_file_path,
        session.set_progress))

    def write_done(fut):
        exc = fut.exception()
        if exc:
            session.set_error(getattr(exc, 'short', str(type(exc))),
                              str(exc))
        else:
            session.set_stage(Stages.DONE)

    write_future.add_done_callback(write_done)
988815
def start(self, *args, **kw):
        
        # Check for a pidfile to see if the daemon already runs
        try:
            pidfile = file(self.pidfile, 'r')
            pid = int(pidfile.read().strip())
            pidfile.close()
        except IOError:
            pid = None

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

        # 
        self.daemonize()
        self.run(*args, **kw)
457460
def daemonize(self):
        
        try:
            pid = os.fork()
            if pid > 0:
                # exit first parent
                sys.exit(0)
        except OSError as e:
            self.logger.error("Fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)

        # decouple from parent environment
        os.chdir("/")
        os.setsid()
        os.umask(0)

        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent
                sys.exit(0)
        except OSError as e:
            self.logger.error("Fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)

        # write pidfile
        atexit.register(self.delpid)
        pid = str(os.getpid())
        with open(self.pidfile,'w+') as f:
            f.write("%s\n" % pid)

        sys.stdout = LoggerProxy(self.logger.info)
        sys.stderr = LoggerProxy(self.logger.error)
542228
def check_parallel_run(self):  # pragma: no cover, not with unit tests...
        
        # TODO: other daemon run on nt
        if os.name == 'nt':  # pragma: no cover, not currently tested with Windows...
            logger.warning("The parallel daemon check is not available on Windows")
            self.__open_pidfile(write=True)
            return

        # First open the pid file in open mode
        self.__open_pidfile()
        try:
            pid_var = self.fpid.readline().strip(' \r\n')
            if pid_var:
                pid = int(pid_var)
                logger.info("Found an existing pid (%s): '%s'", self.pid_filename, pid_var)
            else:
                logger.debug("Not found an existing pid: %s", self.pid_filename)
                return
        except (IOError, ValueError) as err:
            logger.warning("PID file is empty or has an invalid content: %s", self.pid_filename)
            return

        if pid == os.getpid():
            self.pid = pid
            return

        try:
            logger.debug("Testing if the process is running: '%s'", pid)
            os.kill(pid, 0)
        except OSError:
            # consider any exception as a stale pid file.
            # this includes :
            #  * PermissionError when a process with same pid exists but is executed by another user
            #  * ProcessLookupError: [Errno 3] No such process
            self.pre_log.append(("DEBUG", "No former instance to replace"))
            logger.info("A stale pid file exists, reusing the same file")
            return

        if not self.do_replace:
            self.exit_on_error("A valid pid file still exists (pid=%s) and "
                               "I am not allowed to replace. Exiting!" % pid, exit_code=3)

        self.pre_log.append(("DEBUG", "Replacing former instance: %d" % pid))
        try:
            pgid = os.getpgid(pid)
            # SIGQUIT to terminate and dump core
            os.killpg(pgid, signal.SIGQUIT)
        except os.error as err:
            if err.errno != errno.ESRCH:
                raise

        self.fpid.close()
        # TODO: give some time to wait that previous instance finishes?
        time.sleep(1)
        # we must also reopen the pid file in write mode
        # because the previous instance should have deleted it!!
        self.__open_pidfile(write=True)
74058
function writeFile(path, binary, callback) {
  mkdirp(nodePath.dirname(path), function (err) {
    if (err) return callback(err);
    nodeFs.writeFile(path, binary, callback);
  });
}
741889
def mkdir(self, parent, name):
        
        pid = None
        cid = None
        if isinstance(parent, Directory):
            pid = parent.cid
        else:
            raise('Invalid Directory instance.')
        cid = self._req_files_add(pid, name)['cid']
        return self._load_directory(cid)
1353920
def daemonize(self):
        """"""
        self._double_fork()

        # Write pidfile.
        self.pid = os.getpid()

        LOG.info(
            "Succesfully daemonized process {0}.".format(self.pid)
        )
1019136
def atomic_output_file(dest_path, make_parents=False, backup_suffix=None, suffix=".partial.%s"):
  
  if dest_path == os.devnull:
    # Handle the (probably rare) case of writing to /dev/null.
    yield dest_path
  else:
    tmp_path = ("%s" + suffix) % (dest_path, new_uid())
    if make_parents:
      make_parent_dirs(tmp_path)

    yield tmp_path

    # Note this is not in a finally block, so that result won't be renamed to final location
    # in case of abnormal exit.
    if not os.path.exists(tmp_path):
      raise IOError("failure in writing file '%s': target file '%s' missing" % (dest_path, tmp_path))
    if backup_suffix:
      move_to_backup(dest_path, backup_suffix=backup_suffix)
    # If the target already exists, and is a directory, it has to be removed.
    if os.path.isdir(dest_path):
      shutil.rmtree(dest_path)
    shutil.move(tmp_path, dest_path)
257537
@Override
  public synchronized void onNext(final RuntimeStart startTime) {
    if (this.isPidNotWritten()) {
      final long pid = OSUtils.getPID();
      final File outfile = new File(PID_FILE_NAME);
      LOG.log(Level.FINEST, "Storing pid `" + pid + "` in file " + outfile.getAbsolutePath());
      try (final PrintWriter p = new PrintWriter(PID_FILE_NAME, "UTF-8")) {
        p.write(String.valueOf(pid));
        p.write("\n");
      } catch (final FileNotFoundException | UnsupportedEncodingException e) {
        LOG.log(Level.WARNING, "Unable to create PID file.", e);
      }
      this.pidIsWritten = true;
    } else {
      LOG.log(Level.FINEST, "PID already written.");
    }
  }
348833
def _get_pidfile_path(self):
        
        if self.config.daemon.pidfile:
            pidfile = path.abspath(self.config.daemon.pidfile)
            if not os.access(path.dirname(pidfile), os.W_OK):
                raise ValueError('Cannot write to specified pid file path'
                                 ' %s' % pidfile)
            return pidfile
        app = sys.argv[0].split('/')[-1]
        for pidfile in ['%s/pids/%s.pid' % (os.getcwd(), app),
                        '/var/run/%s.pid' % app,
                        '/var/run/%s/%s.pid' % (app, app),
                        '/var/tmp/%s.pid' % app,
                        '/tmp/%s.pid' % app,
                        '%s.pid' % app]:
            if os.access(path.dirname(pidfile), os.W_OK):
                return pidfile
        raise OSError('Could not find an appropriate place for a pid file')
867117
public static boolean isProcessRunning(String baseDir)
    {
        File pidFile = new File(baseDir, "pid");
        boolean exists = pidFile.isFile();
        return exists;
    }
617553
def atomic_write(filename, filesync=False):
  

  tmpf = tempfile.NamedTemporaryFile(delete=False)
  try:
    with open(tmpf.name, 'w') as curfile:
      yield curfile
      if filesync:
        curfile.flush()
        os.fsync(curfile.fileno())
    os.rename(tmpf.name, filename)
  finally:
    try:
      os.remove(tmpf.name)
    except (IOError, OSError):
      pass
356552
def get_pid(rundir, process_type=PROCESS_TYPE, name=None):
    
    pidPath = get_pidpath(rundir, process_type, name)
    log.log('run', 'pidfile for %s %s is %s' % (process_type, name, pidPath))

    if not os.path.exists(pidPath):
        return

    pidFile = open(pidPath, 'r')
    pid = pidFile.readline()
    pidFile.close()
    if not pid or int(pid) == 0:
        return

    return int(pid)
1268876
private void createDirAndFile(Path path) throws IOException {
			// create dir and file first if dir/file not exist
			File file = new File(path.toAbsolutePath().toString());
			File dir = file.getParentFile();
			if (dir != null && !dir.exists()) {
				dir.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
	}
271591
def remove_existing_pidfile(pidfile_path):
    
    try:
        os.remove(pidfile_path)
    except OSError as exc:
        if exc.errno == errno.ENOENT:
            pass
        else:
            raise
79131
def start(self):
        
        # If pidfile already exists, we should read pid from there; to overwrite it, if locking
        # will fail, because locking attempt somehow purges the file contents.
        if os.path.isfile(self.pid):
            with open(self.pid, "r") as old_pidfile:
                old_pid = old_pidfile.read()
        # Create a lockfile so that only one instance of this daemon is running at any time.
        try:
            lockfile = open(self.pid, "w")
        except IOError:
            print("Unable to create the pidfile.")
            sys.exit(1)
        try:
            # Try to get an exclusive lock on the file. This will fail if another process has the file
            # locked.
            fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError:
            print("Unable to lock on the pidfile.")
            # We need to overwrite the pidfile if we got here.
            with open(self.pid, "w") as pidfile:
                pidfile.write(old_pid)
            sys.exit(1)

        # skip fork if foreground is specified
        if not self.foreground:
            # Fork, creating a new process for the child.
            try:
                process_id = os.fork()
            except OSError as e:
                self.logger.error("Unable to fork, errno: {0}".format(e.errno))
                sys.exit(1)
            if process_id != 0:
                if self.keep_fds:
                    # This is the parent process. Exit without cleanup,
                    # see https://github.com/thesharp/daemonize/issues/46
                    os._exit(0)
                else:
                    sys.exit(0)
            # This is the child process. Continue.

            # Stop listening for signals that the parent process receives.
            # This is done by getting a new process id.
            # setpgrp() is an alternative to setsid().
            # setsid puts the process in a new parent group and detaches its controlling terminal.
            process_id = os.setsid()
            if process_id == -1:
                # Uh oh, there was a problem.
                sys.exit(1)

            # Add lockfile to self.keep_fds.
            self.keep_fds.append(lockfile.fileno())

            # Close all file descriptors, except the ones mentioned in self.keep_fds.
            devnull = "/dev/null"
            if hasattr(os, "devnull"):
                # Python has set os.devnull on this system, use it instead as it might be different
                # than /dev/null.
                devnull = os.devnull

            if self.auto_close_fds:
                for fd in range(3, resource.getrlimit(resource.RLIMIT_NOFILE)[0]):
                    if fd not in self.keep_fds:
                        try:
                            os.close(fd)
                        except OSError:
                            pass

            devnull_fd = os.open(devnull, os.O_RDWR)
            os.dup2(devnull_fd, 0)
            os.dup2(devnull_fd, 1)
            os.dup2(devnull_fd, 2)
            os.close(devnull_fd)

        if self.logger is None:
            # Initialize logging.
            self.logger = logging.getLogger(self.app)
            self.logger.setLevel(logging.DEBUG)
            # Display log messages only on defined handlers.
            self.logger.propagate = False

            # Initialize syslog.
            # It will correctly work on OS X, Linux and FreeBSD.
            if sys.platform == "darwin":
                syslog_address = "/var/run/syslog"
            else:
                syslog_address = "/dev/log"

            # We will continue with syslog initialization only if actually have such capabilities
            # on the machine we are running this.
            if os.path.exists(syslog_address):
                syslog = handlers.SysLogHandler(syslog_address)
                if self.verbose:
                    syslog.setLevel(logging.DEBUG)
                else:
                    syslog.setLevel(logging.INFO)
                # Try to mimic to normal syslog messages.
                formatter = logging.Formatter("%(asctime)s %(name)s: %(message)s",
                                              "%b %e %H:%M:%S")
                syslog.setFormatter(formatter)

                self.logger.addHandler(syslog)

        # Set umask to default to safe file permissions when running as a root daemon. 027 is an
        # octal number which we are typing as 0o27 for Python3 compatibility.
        os.umask(0o27)

        # Change to a known directory. If this isn't done, starting a daemon in a subdirectory that
        # needs to be deleted results in "directory busy" errors.
        os.chdir(self.chdir)

        # Execute privileged action
        privileged_action_result = self.privileged_action()
        if not privileged_action_result:
            privileged_action_result = []

        # Change owner of pid file, it's required because pid file will be removed at exit.
        uid, gid = -1, -1

        if self.group:
            try:
                gid = grp.getgrnam(self.group).gr_gid
            except KeyError:
                self.logger.error("Group {0} not found".format(self.group))
                sys.exit(1)

        if self.user:
            try:
                uid = pwd.getpwnam(self.user).pw_uid
            except KeyError:
                self.logger.error("User {0} not found.".format(self.user))
                sys.exit(1)

        if uid != -1 or gid != -1:
            os.chown(self.pid, uid, gid)

        # Change gid
        if self.group:
            try:
                os.setgid(gid)
            except OSError:
                self.logger.error("Unable to change gid.")
                sys.exit(1)

        # Change uid
        if self.user:
            try:
                uid = pwd.getpwnam(self.user).pw_uid
            except KeyError:
                self.logger.error("User {0} not found.".format(self.user))
                sys.exit(1)
            try:
                os.setuid(uid)
            except OSError:
                self.logger.error("Unable to change uid.")
                sys.exit(1)

        try:
            lockfile.write("%s" % (os.getpid()))
            lockfile.flush()
        except IOError:
            self.logger.error("Unable to write pid to the pidfile.")
            print("Unable to write pid to the pidfile.")
            sys.exit(1)

        # Set custom action on SIGTERM.
        signal.signal(signal.SIGTERM, self.sigterm)
        atexit.register(self.exit)

        self.logger.warning("Starting daemon.")

        try:
            self.action(*privileged_action_result)
        except Exception:
            for line in traceback.format_exc().split("\n"):
                self.logger.error(line)