This will terminate (with SIGTERM) the underlying Tor process.

        :returns: a Deferred that callback()'s (with None) when the
            process has actually exited.
191462
def quit(self):
        

        try:
            self.transport.signalProcess('TERM')
            d = Deferred()
            self._on_exit.append(d)

        except error.ProcessExitedAlready:
            self.transport.loseConnection()
            d = succeed(None)
        except Exception:
            d = fail()
        return d
466650
def kill_process(sig = 'TERM')
      content = IO.read(@options[:pid_file])
      pid = content.to_i
      fail("Invalid pid file content #{content.inspect}") if pid == 0
      begin
        Process.kill(sig, pid)
      rescue Errno::ESRCH => e
        fail("Could not find process with pid #{pid}")
      rescue Errno::EPERM => e
        fail("You don't have permissions to stop process #{pid}")
      rescue Exception => e
        fail(e.message)
      end
      true
    end
1329153
def shutdown(self, join=True, timeout=None):
        
        if self.is_alive():  # check if process started
            print("Shutdown initiated")
            self.exit.set()
            if join:
                self.join(timeout=timeout)
                # TODO : timeout before forcing terminate (SIGTERM)

        exitcode = self._process.exitcode if self._process else None  # we return None if the process was never started
        return exitcode
875334
def clean_proc(proc, wait_for_kill=10):
    '''
    
    '''
    # NoneType and other fun stuff need not apply
    if not proc:
        return
    try:
        waited = 0
        while proc.is_alive():
            proc.terminate()
            waited += 1
            time.sleep(0.1)
            if proc.is_alive() and (waited >= wait_for_kill):
                log.error('Process did not die with terminate(): %s', proc.pid)
                os.kill(proc.pid, signal.SIGKILL)
    except (AssertionError, AttributeError):
        # Catch AssertionError when the proc is evaluated inside the child
        # Catch AttributeError when the process dies between proc.is_alive()
        # and proc.terminate() and turns into a NoneType
        pass
1054948
def finish(self):
        ''

        self.finished = True
        self.update(self.maxval)
        self.fd.write('\n')
        if self.signal_set:
            signal.signal(signal.SIGWINCH, signal.SIG_DFL)

        if self.redirect_stderr:
            self._stderr.write(sys.stderr.getvalue())
            sys.stderr = self._stderr

        if self.redirect_stdout:
            self._stdout.write(sys.stdout.getvalue())
            sys.stdout = self._stdout
607124
function () {
        if (!this._tunnel) {
            return q();
        }

        var _this = this;

        this._tunnel.kill('SIGTERM');
        return this._closeDeferred.promise.timeout(3000).fail(function () {
            _this._tunnel.kill('SIGKILL');
            return _this._closeTunnel(-1);
        });
    }
1172122
def exit(self, result=0, msg=None, *args, **kwargs):
    """"""
    if self._finalizer:
      try:
        self._finalizer()
      except Exception as e:
        try:
          NailgunProtocol.send_stderr(
            self._socket,
            '\nUnexpected exception in finalizer: {!r}\n'.format(e)
          )
        except Exception:
          pass

    try:
      # Write a final message to stderr if present.
      if msg:
        NailgunProtocol.send_stderr(self._socket, msg)

      # Send an Exit chunk with the result.
      NailgunProtocol.send_exit_with_code(self._socket, result)

      # Shutdown the connected socket.
      teardown_socket(self._socket)
    finally:
      super(DaemonExiter, self).exit(result=result, *args, **kwargs)
263792
def shutdown(self):
        

        if not self._exited:
            self._exited = True

            # signal task runner to terminate via SIGTERM
            if self._task_runner.is_alive():
                self._task_runner.terminate()

                # if command server is running, then block until
                # task runner completes so it has time to use
                # the command server to clean up root plugins
                if self._command_server.is_alive():
                    if self._task_runner.is_alive():
                        self._task_runner.join()

            _shutdown_pipe(self._pipe)
            self._task.stop()
497132
def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True,
                   timeout=None, on_terminate=None):
    
    if pid == os.getpid():
        raise RuntimeError("I refuse to kill myself")
    parent = psutil.Process(pid)
    children = parent.children(recursive=True)
    if include_parent:
        children.append(parent)
    for p in children:
        p.send_signal(sig)
    gone, alive = psutil.wait_procs(children, timeout=timeout,
                                    callback=on_terminate)
    return (gone, alive)
1295300
def stop(self) -> None:
        
        if not self.running:
            return
        try:
            self.wait(timeout_s=0)
            # If we get here: stopped already
        except subprocess.TimeoutExpired:  # still running
            for kill_level in self.ALL_KILL_LEVELS:
                tried_to_kill = self._terminate(level=kill_level)  # please stop
                if tried_to_kill:
                    try:
                        self.wait(timeout_s=self.kill_timeout_sec)
                        break
                    except subprocess.TimeoutExpired:  # failed to close
                        self.warning("Subprocess didn't stop when asked")
                        pass  # carry on escalating
        self.close_logs()
        self.running = False
634397
def terminate(self, signal_chain=KILL_CHAIN, kill_wait=KILL_WAIT_SEC, purge=True):
    """"""
    alive = self.is_alive()
    if alive:
      logger.debug('terminating {}'.format(self._name))
      for signal_type in signal_chain:
        pid = self.pid
        try:
          logger.debug('sending signal {} to pid {}'.format(signal_type, pid))
          self._kill(signal_type)
        except OSError as e:
          logger.warning('caught OSError({e!s}) during attempt to kill -{signal} {pid}!'
                         .format(e=e, signal=signal_type, pid=pid))

        # Wait up to kill_wait seconds to terminate or move onto the next signal.
        try:
          if self._deadline_until(self.is_dead, 'daemon to exit', timeout=kill_wait):
            alive = False
            logger.debug('successfully terminated pid {}'.format(pid))
            break
        except self.Timeout:
          # Loop to the next kill signal on timeout.
          pass

    if alive:
      raise ProcessManager.NonResponsiveProcess('failed to kill pid {pid} with signals {chain}'
                                      .format(pid=self.pid, chain=signal_chain))

    if purge:
      self.purge_metadata(force=True)
783800
def terminate(self):
        
        self.queue.put(dill.dumps(ExitCommand()))

        if self.process:
            self.process.join()
8444
def stop(self):
        
        if self.pid is None:

            return None

        try:

            while True:

                self.send(signal.SIGTERM)
                time.sleep(0.1)

        except RuntimeError as err:

            if "No such process" in str(err):

                LOG.info("Succesfully stopped the process.")
                return None

            LOG.exception("Failed to stop the process:")
            sys.exit(exit.STOP_FAILED)

        except TypeError as err:

            if "an integer is required" in str(err):

                LOG.info("Succesfully stopped the process.")
                return None

            LOG.exception("Failed to stop the process:")
            sys.exit(exit.STOP_FAILED)
1053853
def on_sigint(self, sig, frame):
        

        if self.stop_requested or self.stop_requested_force:
            # signal has already been sent or we force a shutdown.
            # handles the keystroke 2x CTRL+C to force an exit.
            self.stop_requested_force = True
            self.logger.warning('Force stopped: ' + str(sig))

            # just kill the process, we don't care about the results
            self.on_force_exit()
            os._exit(1)
            # with force_exit we really close the process, killing it in unknown state
            # self.fail('Force stopped', force_exit=True)
            # return

        if self.is_master_process():
            self.logger.warning('Received signal '+str(sig)+'. Send again to force stop. Stopping ...')
        else:
            self.logger.debug("Got child signal " + str(sig))

        self.stop_requested = True

        # the default SIGINT handle in python is not always installed, so we can't rely on the
        # KeyboardInterrupt exception to be thrown.
        # thread.interrupt_main would call sigint again.
        # the shutdown listener will do the rest like committing rest memory files into Git and closing connections.
        sys.exit(0 if self.in_early_stop else 1)
469056
def finish(self):
    
    if self.proc is None:
      return None
    self.proc.stdin.close()
    for thread in (self._out_thread, self._err_thread):
      thread.join()
    (out, err) = [
        b"".join(chunks) for chunks in (self._out_chunks, self._err_chunks)
    ]
    self.proc.stdout.close()
    self.proc.stderr.close()
    if self.proc.returncode:
      err = "\n".join([" ".join(self.cmd), err.decode("utf8")])
      raise IOError(err)
    del self.proc
    self.proc = None
    return out
266351
def _finish(self):
        
        if self._process.returncode is None:
            self._process.stdin.flush()
            self._process.stdin.close()
            self._process.wait()
            self.closed = True
1214334
def daemonize(self):
        
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError as e:
            sys.stderr.write('fork #1 failed: %d (%s)\n' %
                             (e.errno, e.strerror))
            sys.exit(1)
        os.chdir('/')
        os.setsid()
        os.umask(0)
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError as e:
            sys.stderr.write('fork #2 failed: %d (%s)\n' %
                             (e.errno, e.strerror))
            sys.exit(1)
        # to properly close the fd's, we need to use sys and os:
        # http://chromano.me/2011/05/23/starting-python-daemons-via-ssh.html
        sys.stdin.close()
        sys.stdout.close()
        sys.stderr.close()
        os.closerange(0, 3)

        pid = os.getpid()
        with open(self.pid_file, 'w+') as fp:
            fp.write("%s\n" % pid)

        def handler(*args):
            raise BaseException("SIGTERM was caught")
        signal.signal(signal.SIGTERM, handler)
        # atexit functions are "not called when the program is killed by a
        # signal not handled by Python". But since SIGTERM is now handled, the
        # atexit functions do get called.
        atexit.register(self._shutdown)