Write a file with the PID of this server instance.

    Call when setting up a command line testserver.
351443
def write_pid_file():
    
    pidfile = os.path.basename(sys.argv[0])[:-3] + '.pid'  # strip .py, add .pid
    with open(pidfile, 'w') as fh:
        fh.write("%d\n" % os.getpid())
        fh.close()
51511
def _daemonize(self):
        
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #1 failed: %d (%s)\n" %
                             (e.errno, e.strerror))
            sys.exit(1)

        os.setsid()
        os.chdir("/")
        os.umask(0)

        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #2 failed: %d (%s)\n" %
                             (e.errno, e.strerror))
            sys.exit(1)

        sys.stdout.flush()
        sys.stderr.flush()
        if self.stdin:
            si = file(self.stdin, 'r')
            os.dup2(si.fileno(), sys.stdin.fileno())
        if self.stdout:
            so = file(self.stdout, 'a+')
            os.dup2(so.fileno(), sys.stdout.fileno())
        if self.stderr:
            se = file(self.stderr, 'a+', 0)
            os.dup2(se.fileno(), sys.stderr.fileno())
        atexit.register(self.delpid)
        pid = str(os.getpid())
        file(self.pidfile, 'w+').write("%s\n" % pid)
278765
private function writePidFile(string $pidfile, $pid = null)
    {
        if (is_null($pid)) {
            $pid = getmypid();
        }

        file_put_contents($pidfile, $pid) || die(sprintf('Could not write PID information to %s', $pidfile));
    }
990036
private File createAttachFile(int pid) throws IOException {
        String fn = ".attach_pid" + pid;
        String path = "/proc/" + pid + "/cwd/" + fn;
        File f = new File(path);
        try {
            f.createNewFile();
        } catch (IOException x) {
            f = new File(tmpdir, fn);
            f.createNewFile();
        }
        return f;
    }
641658
def start(self, *args):
        

        if os.path.exists(self.pidfile):
            msg = "pidfile exists. Exit.\n"
            sys.stderr.write(msg % self.pidfile)
            sys.exit(1)

        self.daemonize()
        self.run(*args)
1108905
def write
      begin
        FileUtils.mkdir_p(@pid_dir)
        open(@pid_file,'w') { |f| f.write(Process.pid) }
        File.chmod(0644, @pid_file)
      rescue StandardError => e
        ErrorTracker.log(self, "Failed to create PID file", e, nil, :caller)
        raise
      end
      true
    end
1155569
def _write_pidfile(self):
        """"""
        LOGGER.debug('Writing pidfile: %s', self.pidfile_path)
        with open(self.pidfile_path, "w") as handle:
            handle.write(str(os.getpid()))
595242
def write(self, data, debug_info=None):
        
        self.num_write_bytes += len(data)
        if self.debug:
            if not debug_info:
                debug_info = str(len(data))
            sys.stderr.write("%s: WRITE %s:\n%s\n" % (
                self.__class__.__name__,
                debug_info,
                pyhsm.util.hexdump(data)
            ))
        write_sock(self.socket_file, CMD_WRITE, data)
        return read_sock(self.socket_file)
137240
def write(self, out):
        """"""
        out.write_short(self.priority)
        out.write_short(self.weight)
        out.write_short(self.port)
        out.write_name(self.server)
905035
def write_file(self, fp, data):
        """"""
        with open(fp, 'w') as f:
            f.write(data)
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)
611677
private void makeSureServerIsRunning(PortFile portFile)
            throws IOException, InterruptedException {

        if (portFile.exists()) {
            portFile.lock();
            portFile.getValues();
            portFile.unlock();

            if (portFile.containsPortInfo()) {
                // Server seems to already be running
                return;
            }
        }

        // Fork a new server and wait for it to start
        SjavacClient.fork(sjavacForkCmd,
                          portFile,
                          poolsize,
                          keepalive);
    }
1045933
def command_serve(self, host='', port='8000', level='debug'):
        '''
        
        '''
        logging.basicConfig(level=getattr(logging, level.upper()), format=self.format)
        if self.bootstrap:
            logger.info('Bootstraping...')
            self.bootstrap()
        try:
            server_thread = DevServerThread(host, port, self.app)
            server_thread.start()

            wait_for_code_change(extra_files=self.extra_files)
            server_thread.running = False
            server_thread.join()
            logger.info('Reloading...')
            flush_fds()
            pid = os.fork()
            # We need to fork before `execvp` to perform code reload
            # correctly, because we need to complete python destructors and
            # `atexit`.
            # This will save us from problems of incorrect exit, such as:
            # - unsaved data in data storage, which does not write data
            # on hard drive immediatly
            # - code, that can't be measured with coverage tool, because it uses
            # `atexit` handler to save coverage data
            # NOTE: we using untipical fork-exec scheme with replacing
            # the parent process(not the child) to preserve PID of proccess
            # we use `pragma: no cover` here, because parent process cannot be
            # measured with coverage since it is ends with `execvp`
            if pid: # pragma: no cover
                os.closerange(3, MAXFD)
                os.waitpid(pid, 0)
                # reloading the code in parent process
                os.execvp(sys.executable, [sys.executable] + sys.argv)
            else:
                # we closing our recources, including file descriptors
                # and performing `atexit`.
                sys.exit()
        except KeyboardInterrupt:
            logger.info('Stoping dev-server...')
            server_thread.running = False
            server_thread.join()
            sys.exit()
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
42935
def write(self, *args, **kwargs):
        """"""

        self.progress_status()

        # Check abortes state and raise StopIteration if aborted
        if self.aborted:
            statustext = _("File saving aborted.")
            post_command_event(self.main_window, self.main_window.StatusBarMsg,
                               text=statustext)
            return False

        return self.parent_cls.write(self, *args, **kwargs)
641621
def _write_adminfile(kwargs):
    '''
    
    '''
    # Set the adminfile default variables
    email = kwargs.get('email', '')
    instance = kwargs.get('instance', 'quit')
    partial = kwargs.get('partial', 'nocheck')
    runlevel = kwargs.get('runlevel', 'nocheck')
    idepend = kwargs.get('idepend', 'nocheck')
    rdepend = kwargs.get('rdepend', 'nocheck')
    space = kwargs.get('space', 'nocheck')
    setuid = kwargs.get('setuid', 'nocheck')
    conflict = kwargs.get('conflict', 'nocheck')
    action = kwargs.get('action', 'nocheck')
    basedir = kwargs.get('basedir', 'default')

    # Make tempfile to hold the adminfile contents.
    adminfile = salt.utils.files.mkstemp(prefix="salt-")

    def _write_line(fp_, line):
        fp_.write(salt.utils.stringutils.to_str(line))

    with salt.utils.files.fopen(adminfile, 'w') as fp_:
        _write_line(fp_, 'email={0}\n'.format(email))
        _write_line(fp_, 'instance={0}\n'.format(instance))
        _write_line(fp_, 'partial={0}\n'.format(partial))
        _write_line(fp_, 'runlevel={0}\n'.format(runlevel))
        _write_line(fp_, 'idepend={0}\n'.format(idepend))
        _write_line(fp_, 'rdepend={0}\n'.format(rdepend))
        _write_line(fp_, 'space={0}\n'.format(space))
        _write_line(fp_, 'setuid={0}\n'.format(setuid))
        _write_line(fp_, 'conflict={0}\n'.format(conflict))
        _write_line(fp_, 'action={0}\n'.format(action))
        _write_line(fp_, 'basedir={0}\n'.format(basedir))

    return adminfile
882575
def record(session_file, shell, prompt, alias, envvar):
    
    if os.path.exists(session_file):
        click.confirm(
            'File "{0}" already exists. Overwrite?'.format(session_file),
            abort=True,
            default=False,
        )

    secho("We'll do it live!", fg="red", bold=True)
    filename = click.format_filename(session_file)
    secho("RECORDING SESSION: {}".format(filename), fg="yellow", bold=True)

    print_recorder_instructions()

    click.pause()
    click.clear()
    cwd = os.getcwd()  # Save cwd

    # Run the recorder
    commands = run_recorder(shell, prompt, aliases=alias, envvars=envvar)

    os.chdir(cwd)  # Reset cwd

    secho("FINISHED RECORDING SESSION", fg="yellow", bold=True)
    secho("Writing to {0}...".format(filename), fg="cyan")
    with open(session_file, "w", encoding="utf-8") as fp:
        fp.write(HEADER_TEMPLATE.format(shell=shell, prompt=prompt))
        write_directives(fp, "alias", alias)
        write_directives(fp, "env", envvar)
        fp.write("\n")
        fp.write("".join(commands))
        fp.write("\n")

    play_cmd = style("doitlive play {}".format(filename), bold=True)
    echo("Done. Run {} to play back your session.".format(play_cmd))