Daemonize a process
192795
def daemonize(redirect_out=True):
    '''
    
    '''
    # Avoid circular import
    import salt.utils.crypt
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            salt.utils.crypt.reinit_crypto()
            os._exit(salt.defaults.exitcodes.EX_OK)
    except OSError as exc:
        log.error('fork #1 failed: %s (%s)', exc.errno, exc)
        sys.exit(salt.defaults.exitcodes.EX_GENERIC)

    # decouple from parent environment
    os.chdir('/')
    # noinspection PyArgumentList
    os.setsid()
    os.umask(0o022)  # pylint: disable=blacklisted-function

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            salt.utils.crypt.reinit_crypto()
            sys.exit(salt.defaults.exitcodes.EX_OK)
    except OSError as exc:
        log.error('fork #2 failed: %s (%s)', exc.errno, exc)
        sys.exit(salt.defaults.exitcodes.EX_GENERIC)

    salt.utils.crypt.reinit_crypto()

    # A normal daemonization redirects the process output to /dev/null.
    # Unfortunately when a python multiprocess is called the output is
    # not cleanly redirected and the parent process dies when the
    # multiprocessing process attempts to access stdout or err.
    if redirect_out:
        with salt.utils.files.fopen('/dev/null', 'r+') as dev_null:
            # Redirect python stdin/out/err
            # and the os stdin/out/err which can be different
            os.dup2(dev_null.fileno(), sys.stdin.fileno())
            os.dup2(dev_null.fileno(), sys.stdout.fileno())
            os.dup2(dev_null.fileno(), sys.stderr.fileno())
            os.dup2(dev_null.fileno(), 0)
            os.dup2(dev_null.fileno(), 1)
            os.dup2(dev_null.fileno(), 2)
294012
def detach_process():
    
    # see https://pagure.io/python-daemon/blob/master/f/daemon/daemon.py and
    # https://stackoverflow.com/questions/45911705/why-use-os-setsid-in-python
    def fork_then_exit_parent():
        pid = os.fork()
        if pid:  # in parent
            os._exit(0)
    fork_then_exit_parent()
    os.setsid()
    fork_then_exit_parent()
47376
function daemonize(file, conf, args) {
  /* istanbul ignore next: never parse argv in test env */
  args = args || process.argv.slice(2);
  args.unshift(file);
  var logfile = conf.get(ConfigKey.LOGFILE) || '/dev/null'
  //var logfile = conf.get(ConfigKey.LOGFILE) || 'daemon.log'
    , out = fs.openSync(logfile, 'a')
    , err = fs.openSync(logfile, 'a')
    , opts = {
      detached: true,
      stdio: ['ignore', out, err],
      cwd: process.cwd(),
      env: process.env
    };

  //console.dir(logfile);
  //console.dir(args);

  var ps = spawn(cmd, args, opts);
  /* istanbul ignore next: always in test env */
  if(process.env.NODE_ENV !== Constants.TEST) {
    process.exit(0);
  }
  return ps.pid;
}
945252
async function kill(pid) {
  try {
    process.kill(pid, 'SIGTERM')
  } catch (err) {
    if (err.code !== 'ESRCH') throw err
  }
}
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)
857637
def start(self):
        
        if self.pid is not None:

            LOG.error(
                "The process is already running with pid {0}.".format(self.pid)
            )
            sys.exit(exit.ALREADY_RUNNING)

        self.daemonize()

        LOG.info("Beginning run loop for process.")
        try:

            self.run()

        except Exception:

            LOG.exception("Uncaught exception in the daemon run() method.")
            self.stop()
            sys.exit(exit.RUN_FAILURE)
158593
def create_daemon():
    

    try:
        # Fork a child process so the parent can exit.  This returns control to
        # the command-line or shell.  It also guarantees that the child will not
        # be a process group leader, since the child receives a new process ID
        # and inherits the parent's process group ID.  This step is required
        # to insure that the next call to os.setsid is successful.
        pid = os.fork()
    except OSError as err:
        raise Exception("%s [%d]" % (err.strerror, err.errno))

    if pid == 0:  # The first child.
        # To become the session leader of this new session and the process group
        # leader of the new process group, we call os.setsid().  The process is
        # also guaranteed not to have a controlling terminal.
        os.setsid()

        # Is ignoring SIGHUP necessary?
        #
        # It's often suggested that the SIGHUP signal should be ignored before
        # the second fork to avoid premature termination of the process.  The
        # reason is that when the first child terminates, all processes, e.g.
        # the second child, in the orphaned group will be sent a SIGHUP.
        #
        # "However, as part of the session management system, there are exactly
        # two cases where SIGHUP is sent on the death of a process:
        #
        #   1) When the process that dies is the session leader of a session that
        #      is attached to a terminal device, SIGHUP is sent to all processes
        #      in the foreground process group of that terminal device.
        #   2) When the death of a process causes a process group to become
        #      orphaned, and one or more processes in the orphaned group are
        #      stopped, then SIGHUP and SIGCONT are sent to all members of the
        #      orphaned group." [2]
        #
        # The first case can be ignored since the child is guaranteed not to have
        # a controlling terminal.  The second case isn't so easy to dismiss.
        # The process group is orphaned when the first child terminates and
        # POSIX.1 requires that every STOPPED process in an orphaned process
        # group be sent a SIGHUP signal followed by a SIGCONT signal.  Since the
        # second child is not STOPPED though, we can safely forego ignoring the
        # SIGHUP signal.  In any case, there are no ill-effects if it is ignored.
        #
        # import signal           # Set handlers for asynchronous events.
        # signal.signal(signal.SIGHUP, signal.SIG_IGN)

        try:
            # Fork a second child and exit immediately to prevent zombies.  This
            # causes the second child process to be orphaned, making the init
            # process responsible for its cleanup.  And, since the first child is
            # a session leader without a controlling terminal, it's possible for
            # it to acquire one by opening a terminal in the future (System V-
            # based systems).  This second fork guarantees that the child is no
            # longer a session leader, preventing the daemon from ever acquiring
            # a controlling terminal.
            pid = os.fork()  # Fork a second child.
        except OSError as err:
            raise Exception("%s [%d]" % (err.strerror, err.errno))

        if pid == 0:  # The second child.
            # Since the current working directory may be a mounted filesystem, we
            # avoid the issue of not being able to unmount the filesystem at
            # shutdown time by changing it to the root directory.
            os.chdir(WORKDIR)
            # We probably don't want the file mode creation mask inherited from
            # the parent, so we give the child complete control over permissions.
            os.umask(UMASK)
        else:
            # exit() or _exit()?  See below.
            _exit(0)  # Exit parent (the first child) of the second child.
    else:
        # exit() or _exit()?
        # _exit is like exit(), but it doesn't call any functions registered
        # with atexit (and on_exit) or any registered signal handlers.  It also
        # closes any open file descriptors.  Using exit() may cause all stdio
        # streams to be flushed twice and any temporary files may be unexpectedly
        # removed.  It's therefore recommended that child branches of a fork()
        # and the parent branch(es) of a daemon use _exit().
        _exit(0)  # Exit parent of the first child.

    # Close all open file descriptors.  This prevents the child from keeping
    # open any file descriptors inherited from the parent.  There is a variety
    # of methods to accomplish this task.  Three are listed below.
    #
    # Try the system configuration variable, SC_OPEN_MAX, to obtain the maximum
    # number of open file descriptors to close.  If it doesn't exists, use
    # the default value (configurable).
    #
    # try:
    #    maxfd = os.sysconf("SC_OPEN_MAX")
    # except (AttributeError, ValueError):
    #    maxfd = MAXFD
    #
    # OR
    #
    # if os.sysconf_names.has_key("SC_OPEN_MAX"):
    #    maxfd = os.sysconf("SC_OPEN_MAX")
    # else:
    #    maxfd = MAXFD
    #
    # OR
    #
    # Use the getrlimit method to retrieve the maximum file descriptor number
    # that can be opened by this process.  If there is not limit on the
    # resource, use the default value.
    #
    import resource  # Resource usage information.
    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
    if maxfd == resource.RLIM_INFINITY:
        maxfd = MAXFD

    # Iterate through and close all file descriptors.
    for file_desc in range(0, maxfd):
        try:
            os.close(file_desc)
        except OSError:  # file descriptor wasn't open to begin with (ignored)
            pass

    # Redirect the standard I/O file descriptors to the specified file.  Since
    # the daemon has no controlling terminal, most daemons redirect stdin,
    # stdout, and stderr to /dev/null.  This is done to prevent side-effects
    # from reads and writes to the standard I/O file descriptors.

    # This call to open is guaranteed to return the lowest file descriptor,
    # which will be 0 (stdin), since it was closed above.
    os.open(REDIRECT_TO, os.O_RDWR)  # standard input (0)

    # Duplicate standard input to standard output and standard error.
    os.dup2(0, 1)  # standard output (1)
    os.dup2(0, 2)  # standard error (2)

    return 0
107605
function browserify (cmd, args) {
  console.log(cmd, args.join(" "));
  childProcess.fork(require.resolve(cmd + "/bin/cmd"), args.slice());
}
467183
def start(self):
        """"""
        if self.worker is None:
            raise DaemonError('No worker is defined for daemon')

        if os.environ.get('DAEMONOCLE_RELOAD'):
            # If this is actually a reload, we need to wait for the
            # existing daemon to exit first
            self._emit_message('Reloading {prog} ... '.format(prog=self.prog))
            # Orhpan this process so the parent can exit
            self._orphan_this_process(wait_for_parent=True)
            pid = self._read_pidfile()
            if (pid is not None and
                    self._pid_is_alive(pid, timeout=self.stop_timeout)):
                # The process didn't exit for some reason
                self._emit_failed()
                message = ('Previous process (PID {pid}) did NOT '
                           'exit during reload').format(pid=pid)
                self._emit_error(message)
                self._shutdown(message, 1)

        # Check to see if the daemon is already running
        pid = self._read_pidfile()
        if pid is not None:
            # I don't think this should not be a fatal error
            self._emit_warning('{prog} already running with PID {pid}'.format(
                prog=self.prog, pid=pid))
            return

        if not self.detach and not os.environ.get('DAEMONOCLE_RELOAD'):
            # This keeps the original parent process open so that we
            # maintain control of the tty
            self._fork_and_supervise_child()

        if not os.environ.get('DAEMONOCLE_RELOAD'):
            # A custom message is printed for reloading
            self._emit_message('Starting {prog} ... '.format(prog=self.prog))

        self._setup_environment()

        if self.detach:
            self._detach_process()
        else:
            self._emit_ok()

        if self.pidfile is not None:
            self._write_pidfile()

        # Setup signal handlers
        signal.signal(signal.SIGINT, self._handle_terminate)
        signal.signal(signal.SIGQUIT, self._handle_terminate)
        signal.signal(signal.SIGTERM, self._handle_terminate)

        self._run()
1203964
def demonize(self):
        
        # check if a process is already running
        if access(self.pid_file_name, F_OK):
            # read the pid file
            pid = self.read_pid()

            try:
                kill(pid, 0)  # check if process is running
                self.stderr.write("process is already running\n")
                return False
            except OSError as e:
                if e.errno == errno.ESRCH:
                    # process is dead
                    self.delete_pid(force_del=True)
                else:
                    self.stderr.write("demonize failed, something went wrong: %d (%s)\n" % (e.errno, e.strerror))
                    return False

        try:
            pid = fork()
            if pid > 0:
                # Exit from the first parent
                timeout = time() + 60
                while self.read_pid() is None:
                    self.stderr.write("waiting for pid..\n")
                    sleep(0.5)
                    if time() > timeout:
                        break
                self.stderr.write("pid is %d\n" % self.read_pid())
                sys.exit(0)
        except OSError as e:
            self.stderr.write("demonize failed in 1. Fork: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)

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

        # Do the Second fork
        try:
            pid = fork()
            if pid > 0:
                # Exit from the second parent
                sys.exit(0)
        except OSError as e:
            self.stderr.write("demonize failed in 2. Fork: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)

        # Redirect standard file descriptors
        # sys.stdout.flush()
        # sys.stderr.flush()
        # si = file(self.stdin, 'r')
        # so = file(self.stdout, 'a+')
        # se = file(self.stderr, 'a+',
        # os.dup2(si.fileno(), sys.stdin.fileno())
        # os.dup2(so.fileno(), sys.stdout.fileno())
        # os.dup2(se.fileno(), sys.stderr.fileno())

        # Write the PID file
        #atexit.register(self.delete_pid)
        self.write_pid()
        return True
290221
def daemonize(self):
        """"""
        if self.userid:
            uid = pwd.getpwnam(self.userid).pw_uid
            os.seteuid(uid)
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError as err:
            sys.stderr.write("First fork failed: {0} ({1})\n".format(err.errno, err.strerror))
            sys.exit(1)
        # decouple from parent environment
        os.chdir("/")
        os.setsid()
        os.umask(0)

        # Second fork

        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError as err:
            sys.stderr.write("Second fork failed: {0} ({1})\n".format(err.errno, err.strerror))
            sys.exit(1)

        sys.stdout.flush()
        sys.stderr.flush()
        si = open(self.stdin, 'r')
        so = open(self.stdout, 'w')
        se = open(self.stderr, 'w')
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        # write PID file
        atexit.register(self.delpid)
        pid = str(os.getpid())
        open(self.pidfile, 'w').write("%s\n" % pid)
1254672
def start(self, *args, **kw):
        """"""
        pid = None
        if os.path.exists(self.pidfile):
            with open(self.pidfile, 'r') as fp:
                pid = int(fp.read().strip())

        if pid:
            msg = 'pidfile (%s) exists. Daemon already running?\n'
            sys.stderr.write(msg % self.pidfile)
            sys.exit(1)

        self.daemonize()
        self.run(*args, **kw)
460951
protected function daemonize()
	{
		// Is there already an active daemon running?
		if ($this->isActive())
		{
			$this->getLogger()->emergency($this->name . ' daemon is still running. Exiting the application.');

			return false;
		}

		// Reset Process Information
		$this->safeMode = !!@ ini_get('safe_mode');
		$this->processId = 0;
		$this->running = false;

		// Detach process!
		try
		{
			// Check if we should run in the foreground.
			if (!$this->input->get('f'))
			{
				// Detach from the terminal.
				$this->detach();
			}
			else
			{
				// Setup running values.
				$this->exiting = false;
				$this->running = true;

				// Set the process id.
				$this->processId = (int) posix_getpid();
				$this->parentId = $this->processId;
			}
		}
		catch (\RuntimeException $e)
		{
			$this->getLogger()->emergency('Unable to fork.');

			return false;
		}

		// Verify the process id is valid.
		if ($this->processId < 1)
		{
			$this->getLogger()->emergency('The process id is invalid; the fork failed.');

			return false;
		}

		// Clear the umask.
		@ umask(0);

		// Write out the process id file for concurrency management.
		if (!$this->writeProcessIdFile())
		{
			$this->getLogger()->emergency('Unable to write the pid file at: ' . $this->config->get('application_pid_file'));

			return false;
		}

		// Attempt to change the identity of user running the process.
		if (!$this->changeIdentity())
		{
			// If the identity change was required then we need to return false.
			if ($this->config->get('application_require_identity'))
			{
				$this->getLogger()->critical('Unable to change process owner.');

				return false;
			}
			else
			{
				$this->getLogger()->warning('Unable to change process owner.');
			}
		}

		// Setup the signal handlers for the daemon.
		if (!$this->setupSignalHandlers())
		{
			return false;
		}

		// Change the current working directory to the application working directory.
		@ chdir($this->config->get('application_directory'));

		return true;
	}
31530
def daemonize_if(opts):
    '''
    
    '''
    if 'salt-call' in sys.argv[0]:
        return
    if not opts.get('multiprocessing', True):
        return
    if sys.platform.startswith('win'):
        return
    daemonize(False)
882958
def run(self, daemon=False):
        
        from aiida.engine import launch

        # If daemon is True, submit the process and return
        if daemon:
            node = launch.submit(self.process, **self.inputs)
            echo.echo_info('Submitted {}<{}>'.format(self.process_name, node.pk))
            return

        # Otherwise we run locally and wait for the process to finish
        echo.echo_info('Running {}'.format(self.process_name))
        try:
            _, node = launch.run_get_node(self.process, **self.inputs)
        except Exception as exception:  # pylint: disable=broad-except
            echo.echo_critical('an exception occurred during execution: {}'.format(str(exception)))

        if node.is_killed:
            echo.echo_critical('{}<{}> was killed'.format(self.process_name, node.pk))
        elif not node.is_finished_ok:
            arguments = [self.process_name, node.pk, node.exit_status, node.exit_message]
            echo.echo_warning('{}<{}> failed with exit status {}: {}'.format(*arguments))
        else:
            output = []
            echo.echo_success('{}<{}> finished successfully\n'.format(self.process_name, node.pk))
            for triple in sorted(node.get_outgoing().all(), key=lambda triple: triple.link_label):
                output.append([triple.link_label, '{}<{}>'.format(triple.node.__class__.__name__, triple.node.pk)])
            echo.echo(tabulate.tabulate(output, headers=['Output label', 'Node']))
140856
def spawn_daemon(fork=None, pgrpfile=None, outfile='out.txt'):
    ''
    global LAST_PGRP_PATH
    fork = fork or os.fork
    open(outfile, 'a').close()  # TODO: configurable output file
    if pgrpfile and os.path.exists(pgrpfile):
        try:
            cur_pid = int(open(pgrpfile).read().rstrip("\n"))
            os.killpg(cur_pid, 0)
            raise Exception("arbiter still running with pid:" + str(cur_pid))
        except (OSError, ValueError):
            pass
    if fork():  # return True means we are in parent
        return True
    else:
        os.setsid()  # break association with terminal via new session id
        if fork():  # fork one more layer to ensure child will not re-acquire terminal
            os._exit(0)
        LAST_PGRP_PATH = pgrpfile
        if pgrpfile:
            with open(pgrpfile, 'w') as f:
                f.write(str(os.getpgrp()) + "\n")
        logging.root.addHandler(SysLogHandler())
        rotating_out = RotatingStdoutFile(outfile)
        rotating_out.start()
        return False
607089
def run(self):
        '''
        
        '''
        salt.utils.process.appendproctitle(self.__class__.__name__)

        # init things that need to be done after the process is forked
        self._post_fork_init()

        # Make Start Times
        last = int(time.time())

        old_present = set()
        while True:
            now = int(time.time())
            if (now - last) >= self.loop_interval:
                salt.daemons.masterapi.clean_old_jobs(self.opts)
                salt.daemons.masterapi.clean_expired_tokens(self.opts)
                salt.daemons.masterapi.clean_pub_auth(self.opts)
                salt.daemons.masterapi.clean_proc_dir(self.opts)
            self.handle_git_pillar()
            self.handle_schedule()
            self.handle_key_cache()
            self.handle_presence(old_present)
            self.handle_key_rotate(now)
            salt.utils.verify.check_max_open_files(self.opts)
            last = now
            time.sleep(self.loop_interval)