Fork process into background twice to release it from
 the controlling tty. Point open file descriptors shared
 with the parent process to separate destinations (e.g. /dev/null).
434812
def daemonize
      exit if fork
      Process.setsid
      exit if fork
      Dir.chdir('/')
      $stdin.reopen(@stdin)
      $stdout.reopen(@stdout, 'a').sync = true
      $stderr.reopen(@stderr, 'a').sync = true
      File.open(@pid, 'w') {|f| f.write(Process.pid) }
      at_exit { delete_pid }
      trap('TERM') { exit }
    end
55284
def pause_process(self, key):
        """"""
        if key in self.processes and key not in self.paused:
            os.killpg(os.getpgid(self.processes[key].pid), signal.SIGSTOP)
            self.queue[key]['status'] = 'paused'
            self.paused.append(key)
            return True
        return False
773301
private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!h.compareAndSetWaitStatus(Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !h.compareAndSetWaitStatus(0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }
352412
def _double_fork(self):
        
        try:

            pid = os.fork()
            if pid > 0:

                # Exit first parent.
                sys.exit(0)
                return None

        except OSError as err:

            LOG.exception(
                "Fork #1 failed: {0} ({1})".format(
                    err.errno,
                    err.strerror,
                ),
            )
            sys.exit(exit.DAEMONIZE_FAILED)
            return None

        # 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 err:

            LOG.exception(
                "Fork #2 failed: {0} ({1})".format(
                    err.errno,
                    err.strerror,
                ),
            )
            sys.exit(exit.DAEMONIZE_FAILED)
            return None
808618
def os_forkpty_wrapper():
    """"""
    pid = None
    prepare_to_fork_acquire()
    try:
        pid, fd = _orig_os_forkpty()
    finally:
        if pid == 0:
            child_after_fork_release()
        else:
            parent_after_fork_release()
    return pid, fd
551612
function interceptDeath(process, events) {
    var closeEvent = helpers.support.close;

    // all channels are closed
    process.once(closeEvent ? 'close' : 'exit', events.close);

    // the process died
    if (closeEvent) {
      process.once('exit', events.exit);
    } else {

      // intercept internal onexit call
      var internalHandle = process._internal.onexit;
      process._internal.onexit = function () {
        events.exit();
        internalHandle.apply(this, arguments);
      };
    }
  }
1297082
function (args, detached, callback) {
  let error, errorEmitted, stderr, stdout

  try {
    // Ensure we don't spawn multiple squirrel processes
    // Process spawned, same args:        Attach events to alread running process
    // Process spawned, different args:   Return with error
    // No process spawned:                Spawn new process
    if (spawnedProcess && !isSameArgs(args)) {
      // Disabled for backwards compatibility:
      // eslint-disable-next-line standard/no-callback-literal
      return callback(`AutoUpdater process with arguments ${args} is already running`)
    } else if (!spawnedProcess) {
      spawnedProcess = spawn(updateExe, args, {
        detached: detached,
        windowsHide: true
      })
      spawnedArgs = args || []
    }
  } catch (error1) {
    error = error1

    // Shouldn't happen, but still guard it.
    process.nextTick(function () {
      return callback(error)
    })
    return
  }
  stdout = ''
  stderr = ''

  spawnedProcess.stdout.on('data', (data) => { stdout += data })
  spawnedProcess.stderr.on('data', (data) => { stderr += data })

  errorEmitted = false
  spawnedProcess.on('error', (error) => {
    errorEmitted = true
    callback(error)
  })

  return spawnedProcess.on('exit', function (code, signal) {
    spawnedProcess = undefined
    spawnedArgs = []

    // We may have already emitted an error.
    if (errorEmitted) {
      return
    }

    // Process terminated with error.
    if (code !== 0) {
      // Disabled for backwards compatibility:
      // eslint-disable-next-line standard/no-callback-literal
      return callback(`Command failed: ${signal != null ? signal : code}\n${stderr}`)
    }

    // Success.
    callback(null, stdout)
  })
}
1328689
def start

      unless @allow_multiple
        if running?
          log(:error, "\"#{@name}\" is already running (PID: #{@pid})")
          return
        end
      end

      @pid = fork do
        begin
          Process.setsid

          open(@pid_file, 'w') do |f|
            f << Process.pid
            @pid = Process.pid
          end

          execute_callback(:before_start)

          Dir.chdir @path.to_s
          File.umask 0000

          if @logger
            log = File.new(@log_file, "a")
            log.sync = @sync_log

            STDIN.reopen "/dev/null"
            STDOUT.reopen log
            STDERR.reopen STDOUT
          end

          trap("TERM") do
            stop
          end

          execute_callback(:start)

        rescue RuntimeError => message
          STDERR.puts message
          STDERR.puts message.backtrace

          execute_callback(:error)
        rescue => message
          STDERR.puts message
          STDERR.puts message.backtrace

          execute_callback(:error)
        end
      end

    rescue => message
      STDERR.puts message
      STDERR.puts message.backtrace
      execute_callback(:error)
    end
1201041
def Attach(self, pid):
    """"""
    if self.inferior.is_running:
      answer = raw_input('Already attached to process ' +
                         str(self.inferior.pid) +
                         '. Detach? [y]/n ')
      if answer and answer != 'y' and answer != 'yes':
        return None
      self.Detach()
    # Whatever position we had before will not make any sense now
    for plugin in self.plugins:
      plugin.position = None
    self.inferior.Reinit(pid)
630786
def createDaemon():
   

   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, e:
      raise Exception, "%s [%d]" % (e.strerror, e.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, e:
         raise Exception, "%s [%d]" % (e.strerror, e.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.
         os._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().
      os._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
  
   # FIXME: this breaks our tpxmld, so it's commented for now //kll
   # Iterate through and close all file descriptors.
#   for fd in range(0, maxfd):
#      try:
#         os.close(fd)
#      except OSError:   # ERROR, fd 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)
961292
def release_singleton(self):
        '''
       '''
        with suppress(KeyError):
            del self.cfg['is_programming_running_info']
        with suppress(FileNotFoundError, AttributeError):
            os.remove(self.check_file)
1231248
def kill_process_children_unix(pid):
    
    root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
    if not os.path.isfile(root_process_path):
        return
    with open(root_process_path) as children_list_file:
        children_list_pid = children_list_file.read().split()

    for child_pid in children_list_pid:
        children_proc_path = "/proc/%s/task/%s/children" % (
            child_pid,
            child_pid,
        )
        if not os.path.isfile(children_proc_path):
            continue
        with open(children_proc_path) as children_list_file_2:
            children_list_pid_2 = children_list_file_2.read().split()
        for _pid in children_list_pid_2:
            try:
                os.kill(int(_pid), signal.SIGTERM)
            except ProcessLookupError:
                continue
        try:
            os.kill(int(child_pid), signal.SIGTERM)
        except ProcessLookupError:
            continue
940375
def run_external_subprocess_in_background(command_list, env=None):
    """"""
    if system_os == "Windows":
        DETACHED_PROCESS = 0x00000008
        p = subprocess.Popen(command_list, shell=False, stdin=None, stdout=None,
                stderr=None, close_fds=True, creationflags=DETACHED_PROCESS, env=env)
    else:
        p = subprocess.Popen(command_list, shell=False, stdin=None, stdout=None,
                stderr=None, close_fds=True, env=env)
    return p
267491
def suspend_to_background(self, suspend_group=True):
        
        # Only suspend when the opperating system supports it.
        # (Not on Windows.)
        if hasattr(signal, 'SIGTSTP'):
            def run():
                # Send `SIGSTP` to own process.
                # This will cause it to suspend.

                # Usually we want the whole process group to be suspended. This
                # handles the case when input is piped from another process.
                if suspend_group:
                    os.kill(0, signal.SIGTSTP)
                else:
                    os.kill(os.getpid(), signal.SIGTSTP)

            self.run_in_terminal(run)
615828
function () {
    const oThis = this
    ;

    oThis.snmData.lastProcessedBlock = oThis.toBlock;

    fs.writeFileSync(
      oThis.filePath,
      JSON.stringify(oThis.snmData),
      function (err) {
        if (err)
          logger.error(err);
      }
    );

    if (oThis.interruptSignalObtained) {
      logger.info('Exiting Process....');
      process.exit(1);
    }
  }
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
845792
def daemonize(logfile):
    
    
    # turn off GC across the fork
    gc.collect(2)
    gc.collect(1)
    gc.collect(0)
    gc.disable()
    
    child_pid = os.fork()

    if child_pid == 0:
        # child!
        sys.stdin.close()
        os.dup2(logfile.fileno(), sys.stdout.fileno())
        os.dup2(logfile.fileno(), sys.stderr.fileno())

        soft_num_open_files, hard_num_open_files = resource.getrlimit(resource.RLIMIT_NOFILE)
        if hard_num_open_files == resource.RLIM_INFINITY:
            # guess
            hard_num_open_files = 1024

        # we don't have many other fds open yet
        for i in range(3, hard_num_open_files):
            if i == logfile.fileno():
                continue

            try:
                os.close(i)
            except:
                pass

        os.setsid()

        daemon_pid = os.fork()
        if daemon_pid == 0:
            # daemon! chdir and return
            os.chdir('/')
            gc.enable()
            gc.collect(2)
            gc.collect(1)
            gc.collect(0)
            return 0

        elif daemon_pid > 0:
            # parent (intermediate child)
            sys.exit(0)

        else:
            # error
            sys.exit(1)

    elif child_pid > 0:
        # grand-parent (caller)
        # re-activate gc
        gc.enable()
        gc.collect(2)
        gc.collect(1)
        gc.collect(0)

        # wait for intermediate child.
        # panic if we don't hear back after 5 minutes
        timeout = 600
        if BLOCKSTACK_TEST:
            # wait around so we can attach gdb or whatever
            timeout = 60000

        for i in range(0, timeout):
            pid, status = os.waitpid(child_pid, os.WNOHANG)
            if pid == 0:
                # still waiting
                time.sleep(1)
                log.debug("Still waiting on {}".format(child_pid))
                continue

            # child has exited!
            if os.WEXITSTATUS(status) == 0:
                return child_pid
            else:
                log.error("Child exit status {}".format(status))
                return -1

        # child has not exited yet.  This is not okay.
        log.error("Child PID={} did not exit.  Killing it instead and failing...".format(child_pid))
        os.kill(child_pid, signal.SIGKILL)
        return -1
    
    else:
        # failed to fork 
        log.error("Failed to fork")
        return -1

    # parent! success
    return child_pid