Signals the child process to gracefully terminate
491057
function signalTerm(childProcess, callback) {
  childProcess.emit('signalTerm');
  if (IS_WINDOWS) {
    // On Windows, there is no such way as SIGTERM or SIGINT. The closest
    // thing is to interrupt the process with Ctrl+C. Under the hood, that
    // generates '\u0003' character on stdin of the process and if
    // the process listens on stdin, it's able to catch this as 'SIGINT'.
    //
    // However, that only works if user does it manually. There is no
    // way to do it programmatically, at least not in Node.js (and even
    // for C/C++, all the solutions are dirty hacks). Even if you send
    // the very same character to stdin of the process, it's not
    // recognized (the rl.on('SIGINT') event won't get triggered)
    // for some reason.
    //
    // The only thing Dredd is left with is a convention. So when Dredd
    // wants to gracefully signal to the child process it should terminate,
    // it sends the '\u0003' to stdin of the child. It's up to the child
    // to implement reading from stdin in such way it works both for
    // programmatic and manual Ctrl+C.
    childProcess.stdin.write(String.fromCharCode(ASCII_CTRL_C));
  } else {
    childProcess.kill('SIGTERM');
  }
  process.nextTick(callback);
}
93550
def _terminate(self, level: int) -> bool:
        
        if not self.running:
            return True

        # Already closed by itself?
        try:
            self.wait(0)
            return True
        except subprocess.TimeoutExpired:  # failed to close
            pass

        # SEE NOTES ABOVE. This is tricky under Windows.

        suffix = " [to child process {}]".format(self.process.pid)
        if level == self.KILL_LEVEL_CTRL_C_OR_SOFT_KILL:
            if WINDOWS:
                success = 0 != ctypes.windll.kernel32.GenerateConsoleCtrlEvent(
                    CTRL_C_EVENT, self.process.pid)
                if success:
                    self.info("Sent CTRL-C to request stop" + suffix)
                    # ... but that doesn't mean it'll stop...
                else:
                    self.info("Failed to send CTRL-C" + suffix)
                return success
            else:
                self.warning("Asking process to stop (SIGTERM)" + suffix)
                self.process.terminate()  # soft kill under POSIX
                return True

        elif level == self.KILL_LEVEL_CTRL_BREAK:
            if not WINDOWS:
                return False
            success = 0 != ctypes.windll.kernel32.GenerateConsoleCtrlEvent(
                CTRL_BREAK_EVENT, self.process.pid)
            if success:
                self.info("Sent CTRL-BREAK to request stop" + suffix)
            else:
                self.info("Failed to send CTRL-BREAK" + suffix)
            return success

        elif level == self.KILL_LEVEL_TASKKILL:
            if not WINDOWS:
                return False
            retcode = self._taskkill(force=False)  # does its own info messages
            return retcode == winerror.ERROR_SUCCESS

        elif level == self.KILL_LEVEL_TASKKILL_FORCE:
            if not WINDOWS:
                return False
            retcode = self._taskkill(force=True)  # does its own info messages
            return retcode == winerror.ERROR_SUCCESS

        elif level == self.KILL_LEVEL_HARD_KILL:
            # Last resort
            self._kill()  # may do TASKKILL /F or some other method
            return True

        else:
            raise ValueError("Bad kill level requested")
304192
def kill_child_processes(parent_proc):
    
    logging.debug("Killing stress process")
    try:
        for proc in parent_proc.children(recursive=True):
            logging.debug('Killing %s', proc)
            proc.kill()
        parent_proc.kill()
    except AttributeError:
        logging.debug('No such process')
        logging.debug('Could not kill process')
1079823
def signal_terminate(on_terminate):
    """"""
    for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]:
        signal.signal(i, on_terminate)
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)
547902
public static void terminateProcess(String pid) {
    ShellCommandExecutor shexec = null;
    String errMsg = null;
    try {
      String[] args = { "kill", pid };
      shexec = new ShellCommandExecutor(args);
      shexec.execute();
    } catch (IOException ioe) {
      // Do nothing, we log the exit code in the finally block.
      errMsg = ioe.getMessage();
    } finally {
      LOG.info("Killing process " + pid +
               " with SIGTERM. Exit code " + shexec.getExitCode() +
               (errMsg == null ? "" : " (" + errMsg + ")"));
    }
  }
776199
def terminate(pid, sig, timeout):
    ''''''
    os.kill(pid, sig)
    start = time.time()
    while True:
        try:
            # This is requireed if it's our child to avoid zombie. Also
            # is_running() returns True for zombie process.
            _, status = os.waitpid(pid, os.WNOHANG)
        except OSError as exc:
            if exc.errno != errno.ECHILD: # pragma: nocover
                raise
        else:
            if status:
                return True
        if not is_running(pid):
            return True
        if time.time()-start>=timeout:
            return False
        time.sleep(0.1)
103342
def _AbortKill(self):
    """"""
    for pid, process in iter(self._processes_per_pid.items()):
      if not process.is_alive():
        continue

      logger.warning('Killing process: {0:s} (PID: {1:d}).'.format(
          process.name, pid))
      self._KillProcess(pid)
978980
def stop_process(process):
    """"""
    process.terminate()
    process.join(3)

    if process.is_alive() and os.name != 'nt':
        try:
            os.kill(process.pid, signal.SIGKILL)
            process.join()
        except OSError:
            return

    if process.is_alive():
        raise RuntimeError("Unable to terminate PID %d" % os.getpid())
227109
function check() {
    if (terminated) {
      // Successfully terminated
      clearTimeout(t);
      return callback();
    }
    if ((Date.now() - start) < timeout) {
      // Still not terminated, try again
      signalTerm(childProcess, (err) => {
        if (err) { return callback(err); }
        t = setTimeout(check, retryDelay);
      });
    } else {
      // Still not terminated and the timeout has passed, either
      // kill the process (force) or provide an error
      clearTimeout(t);
      if (force) {
        signalKill(childProcess, callback);
      } else {
        callback(
          new Error(`Unable to gracefully terminate process ${childProcess.pid}`)
        );
      }
    }
  }
140553
def _AbortTerminate(self):
    """"""
    for pid, process in iter(self._processes_per_pid.items()):
      if not process.is_alive():
        continue

      logger.warning('Terminating process: {0:s} (PID: {1:d}).'.format(
          process.name, pid))
      process.terminate()
668908
def stop(self):
        

        if self.original_handler is not None:
            signal.signal(signal.SIGWINCH, self.original_handler)
643571
def scram(self):
        '''

        '''
        self.stop_all_children()
        signal.signal(signal.SIGTERM, signal.SIG_DFL)
        sys.exit(2)
937973
void monitorChild() {
    Process proc = childProc;
    if (proc == null) {
      // Process may have already been disposed of, e.g. by calling kill().
      return;
    }

    while (proc.isAlive()) {
      try {
        proc.waitFor();
      } catch (Exception e) {
        LOG.log(Level.WARNING, "Exception waiting for child process to exit.", e);
      }
    }

    synchronized (this) {
      if (isDisposed()) {
        return;
      }

      int ec;
      try {
        ec = proc.exitValue();
      } catch (Exception e) {
        LOG.log(Level.WARNING, "Exception getting child process exit code, assuming failure.", e);
        ec = 1;
      }

      if (ec != 0) {
        State currState = getState();
        // Override state with failure if the current state is not final, or is success.
        if (!currState.isFinal() || currState == State.FINISHED) {
          setState(State.FAILED, true);
        }
      }

      dispose();
    }
  }
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)
843995
function serverClose (signal, done) {
  _logger.info('Process received ' + signal + ', exiting ....')
  if (done === undefined) {
    done = function () {
      process.exit(0)
    }
  }
  if (server) {
    server.close(done)
  } else {
    done()
  }
}
1008116
def terminate(self):
        """"""
        if self._process.state() == QProcess.Running:
            try:
                self._process.terminate()
            except Exception:
                pass
        self._fired = True