Python os.killpg() Examples

The following are 30 code examples of os.killpg(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: __init__.py    From aetros-cli with MIT License 10 votes vote down vote up
def raise_sigint():
    """
    Raising the SIGINT signal in the current process and all sub-processes.

    os.kill() only issues a signal in the current process (without subprocesses).
    CTRL+C on the console sends the signal to the process group (which we need).
    """
    if hasattr(signal, 'CTRL_C_EVENT'):
        # windows. Need CTRL_C_EVENT to raise the signal in the whole process group
        os.kill(os.getpid(), signal.CTRL_C_EVENT)
    else:
        # unix.
        pgid = os.getpgid(os.getpid())
        if pgid == 1:
            os.kill(os.getpid(), signal.SIGINT)
        else:
            os.killpg(os.getpgid(os.getpid()), signal.SIGINT) 
Example #2
Source File: start.py    From cf-mendix-buildpack with Apache License 2.0 8 votes vote down vote up
def terminate_process():
    if m2ee:
        logging.info("stopping app...")
        if not m2ee.stop():
            if not m2ee.terminate():
                m2ee.kill()
    try:
        this_process = os.getpgid(0)
        logging.debug(
            "Terminating process group with pgid=%s", format(this_process)
        )
        os.killpg(this_process, signal.SIGTERM)
        time.sleep(3)
        os.killpg(this_process, signal.SIGKILL)
    except OSError:
        logging.exception("Failed to terminate all child processes") 
Example #3
Source File: tools.py    From Dallinger with MIT License 6 votes vote down vote up
def stop(self, signal=None):
        """Stop the heroku local subprocess and all of its children.
        """
        signal = signal or self.int_signal
        self.out.log("Cleaning up local Heroku process...")
        if self._process is None:
            self.out.log("No local Heroku process was running.")
            return

        try:
            os.killpg(os.getpgid(self._process.pid), signal)
            self.out.log("Local Heroku process terminated.")
        except OSError:
            self.out.log("Local Heroku was already terminated.")
            self.out.log(traceback.format_exc())
        finally:
            self._process = None 
Example #4
Source File: ros_agent.py    From scenario_runner with MIT License 6 votes vote down vote up
def destroy(self):
        """
        Cleanup of all ROS publishers
        """
        if self.stack_process and self.stack_process.poll() is None:
            rospy.loginfo("Sending SIGTERM to stack...")
            os.killpg(os.getpgid(self.stack_process.pid), signal.SIGTERM)
            rospy.loginfo("Waiting for termination of stack...")
            self.stack_process.wait()
            time.sleep(5)
            rospy.loginfo("Terminated stack.")

        rospy.loginfo("Stack is no longer running")
        self.world_info_publisher.unregister()
        self.map_file_publisher.unregister()
        self.vehicle_status_publisher.unregister()
        self.vehicle_info_publisher.unregister()
        self.waypoint_publisher.unregister()
        self.stack_process = None
        rospy.loginfo("Cleanup finished") 
Example #5
Source File: brohttpdriver.py    From sniffer with Apache License 2.0 6 votes vote down vote up
def stop(self):
        self.logger.warn("bro stop...")
        if not self.running:
            self.logger.warn("bro running:{}".format(self.running))
            return

        self.running = False
        gevent.sleep(2)
        self.client_task = None

        if self.sub_task is not None:
            try:
                self.logger.warn("bro killpg({})...".format(self.sub_task.pid))
                os.killpg(self.sub_task.pid, signal.SIGTERM)
                self.logger.warn("bro killpg({}) down.".format(self.sub_task.pid))
            except Exception as ex:
                self.logger.error("fail to kill the process, %s", ex)
                traceback.print_exc()
            self.sub_task.wait()
            self.sub_task = None

        self.logger.warn("bro stop down.") 
Example #6
Source File: tsharkhttpsdriver.py    From sniffer with Apache License 2.0 6 votes vote down vote up
def stop(self):
        self.logger.info("stop tshark driver on interface %s for ports %s, with bpf filter %s", self.interface,
                         self.ports, self.bpf_filter)
        self.running = False
        if self.client_task:
            self.client_task.join(timeout=2)
            self.client_task = None

        if self.sub_task is not None:
            try:
                if self.sub_task.isalive():
                    os.killpg(self.sub_task.pid, signal.SIGTERM)
                    self.sub_task.wait()
            except Exception as ex:
                traceback.print_exc()
                self.logger.error("fail to kill subprocess %s", ex)
            self.sub_task = None 
Example #7
Source File: tracer.py    From judge-server with GNU Affero General Public License v3.0 6 votes vote down vote up
def _shocker_thread(self):
        # On Linux, ignored signals still cause a notification under ptrace.
        # Hence, we use SIGWINCH, harmless and ignored signal to make wait4 return
        # pt_process::monitor, causing time to be updated.
        # On FreeBSD, a signal must not be ignored in order for wait4 to return.
        # Hence, we swallow SIGSTOP, which should never be used anyway, and use it
        # force an update.
        wake_signal = signal.SIGSTOP if 'freebsd' in sys.platform else signal.SIGWINCH
        self._spawned_or_errored.wait()

        while not self._died.wait(1):
            if self.execution_time > self._time or self.wall_clock_time > self._wall_time:
                log.warning('Shocker activated and killed %d', self.pid)
                self.kill()
                self._is_tle = True
                break
            try:
                os.killpg(self.pid, wake_signal)
            except OSError:
                pass 
Example #8
Source File: trivup.py    From trivup with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def stop(self, wait_term=True, force=False):
        if self.state != 'started':
            return

        self.dbg('Stopping (pid {})'.format(self.proc.pid))
        try:
            os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
        except OSError as e:
            self.log('killpg() failed: already dead? (%s): ignoring' % str(e))
            wait_term = False

        if wait_term:
            # Wait for termination
            self.wait_stopped(timeout=10, force=force)
        else:
            self.state = 'stopped'

        self.dbg('now %s, runtime %ds' % (self.state, self.runtime()))

        self.stdout_fd.close()
        self.stderr_fd.close()
        self.proc = None 
Example #9
Source File: compiled_executor.py    From judge-server with GNU Affero General Public License v3.0 6 votes vote down vote up
def _shocker_thread(self) -> None:
        # Though this shares a name with the shocker thread used for submissions, where the process shocker thread
        # is a fine scalpel that ends a TLE process with surgical precision, this is more like a rusty hatchet
        # that beheads a misbehaving compiler.
        #
        # It's not very accurate: time starts ticking in the next line, regardless of whether the process is
        # actually running, and the time is updated in 0.25s intervals. Nonetheless, it serves the purpose of
        # not allowing the judge to die.
        #
        # See <https://github.com/DMOJ/judge/issues/141>
        start_time = time.time()

        while self.returncode is None:
            if time.time() - start_time > self._time:
                self.timed_out = True
                try:
                    os.killpg(self.pid, signal.SIGKILL)
                except OSError:
                    # This can happen if the process exits quickly
                    pass
                break
            time.sleep(0.25) 
Example #10
Source File: __init__.py    From loopchain with Apache License 2.0 6 votes vote down vote up
def exit_and_msg(msg):
    traceback.print_stack()

    exit_msg = "Service Stop by: " + msg
    logging.exception(exit_msg)

    # To make sure of terminating process exactly
    os.killpg(0, signal.SIGKILL)
    time.sleep(5)

    os.kill(os.getpid(), signal.SIGKILL)
    time.sleep(5)

    os._exit(-1)
    time.sleep(5)

    sys.exit(-1) 
Example #11
Source File: __init__.py    From hacker-scripts with MIT License 6 votes vote down vote up
def stop(self):
        if self.process is None:
            return
        try:
            os.killpg(os.getpgid(self.process.pid), self.stop_signal)
        except OSError:
            # Process is already gone
            pass
        else:
            kill_time = time.time() + self.kill_after
            while time.time() < kill_time:
                if self.process.poll() is not None:
                    break
                time.sleep(0.25)
            else:
                try:
                    os.killpg(os.getpgid(self.process.pid), 9)
                except OSError:
                    # Process is already gone
                    pass
        self.process = None 
Example #12
Source File: control.py    From civet with Apache License 2.0 6 votes vote down vote up
def kill_proc(self, proc):
        """
        Stop the process if it is alive.
        Input:
          proc: dict: as created in start_proc()
        Return:
          str: information on what happened
        """
        if proc["process"].poll() == None:
            try:
                pgid = os.getpgid(proc["process"].pid)
                os.killpg(pgid, signal.SIGTERM)
            except:
                """
                Could already be dead
                """
            proc["process"].terminate()
            proc["runtime"] = time.time() - proc["start"]
            proc["running"] = False
            return "Process %s killed" % proc["process"].pid
        return "" 
Example #13
Source File: webscreenshot.py    From webscreenshot with GNU Lesser General Public License v3.0 6 votes vote down vote up
def kill_em_all(sig, frame):
    """
        Terminate all processes while capturing a SIGINT from the user
    """
    logger_gen.info('CTRL-C received, exiting')
    if is_windows():
        multiprocessing.sys.exit(1)
    
    else:
        pid = os.getpid()
        pgid = os.getpgid(pid)
        sid = os.getsid(os.getpid())
        
        # if launched with --no-xserver
        if pid == sid:
            os.killpg(pgid, signal.SIGKILL)
        else:
            time.sleep(4)
            multiprocessing.sys.exit(1) 
Example #14
Source File: kill.py    From pulsar with Apache License 2.0 6 votes vote down vote up
def __kill_posix(pid):
    def __check_pid():
        try:
            os.kill(pid, 0)
            return True
        except OSError:
            return False

    if __check_pid():
        for sig in [15, 9]:
            try:
                os.killpg(pid, sig)
            except OSError:
                return
            sleep(1)
            if not __check_pid():
                return 
Example #15
Source File: afl_multikill.py    From afl-utils with Apache License 2.0 6 votes vote down vote up
def kill_session(session):
    if os.path.isfile("/tmp/afl_multicore.PGID.%s" % session):
        f = open("/tmp/afl_multicore.PGID.%s" % session)
        pgids = f.readlines()

        for pgid in pgids:
            try:
                print_ok("Killing jobs with PGID %s" % pgid.strip('\r\n'))
                os.killpg(int(pgid), signal.SIGTERM)
            except ProcessLookupError:
                print_warn("No processes with PGID %s found!" % (pgid.strip('\r\n')))

        f.close()
        os.remove("/tmp/afl_multicore.PGID.%s" % session)
    else:
        print_err("PGID file '/tmp/afl_multicore.PGID.%s' not found! Aborting!" % session)
        sys.exit(1) 
Example #16
Source File: integ_test_base.py    From TabPy with MIT License 6 votes vote down vote up
def tearDown(self):
        # stop TabPy
        if self.process is not None:
            if platform.system() == "Windows":
                subprocess.call(["taskkill", "/F", "/T", "/PID", str(self.process.pid)])
            else:
                os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
            self.process.kill()

            # after shutting down TabPy and before we start it again
            # for next test give it some time to terminate.
            time.sleep(5)

        # remove temporary files
        if self.delete_temp_folder:
            os.remove(self.state_file_name)
            os.remove(self.config_file_name)
            shutil.rmtree(self.tmp_dir)

        super(IntegTestBase, self).tearDown() 
Example #17
Source File: _service_manager.py    From cotyledon with Apache License 2.0 5 votes vote down vote up
def _reload(self):
        """reload all children

        posix only
        """
        self._run_hooks('reload')

        # Reset forktimes to respawn services quickly
        self._forktimes = []
        signal.signal(signal.SIGHUP, signal.SIG_IGN)
        os.killpg(0, signal.SIGHUP)
        signal.signal(signal.SIGHUP, self._signal_catcher) 
Example #18
Source File: processpipe.py    From blissflixx with GNU General Public License v2.0 5 votes vote down vote up
def stop(self):
    if self.proc is not None:
      # Stop gets called from a seperate thread 
      # so shutdown may already be in progress
      # when we try to kill - therefore ignore errors
      try:
        # kill - including all children of process
        self.killing = True
        os.killpg(self.proc.pid, signal.SIGKILL)
      except Exception, e:
        pass 
Example #19
Source File: ios_ssh.py    From decrypt-ios-apps-script with MIT License 5 votes vote down vote up
def cleanup():
	if ssh_client != None and ssh_client.get_transport() != None and ssh_client.get_transport().is_active():
		print "[+] Stopping SSH connection"
		ssh_client.close()

	global itnl_pid
	if itnl_pid != None:
		print "[+] Stopping iTunnel"
		os.killpg(os.getpgid(itnl_pid), signal.SIGTERM)
		itnl_pid = None

	sys.exit() 
Example #20
Source File: encode_lib_common.py    From atac-seq-pipeline with MIT License 5 votes vote down vote up
def run_shell_cmd(cmd):
    p = subprocess.Popen(
        ['/bin/bash', '-o', 'pipefail'],  # to catch error in pipe
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        preexec_fn=os.setsid)  # to make a new process with a new PGID
    pid = p.pid
    pgid = os.getpgid(pid)
    log.info('run_shell_cmd: PID={}, PGID={}, CMD={}'.format(pid, pgid, cmd))
    stdout, stderr = p.communicate(cmd)
    rc = p.returncode
    err_str = 'PID={}, PGID={}, RC={}\nSTDERR={}\nSTDOUT={}'.format(
        pid, pgid, rc, stderr.strip(), stdout.strip())
    if rc:
        # kill all child processes
        try:
            os.killpg(pgid, signal.SIGKILL)
        except:
            pass
        finally:
            raise Exception(err_str)
    else:
        log.info(err_str)
    return stdout.strip('\n')

# math 
Example #21
Source File: ptys.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def killpg(self, sig = signal.SIGTERM):
		"""Send a signal to the process group of the process in the pty"""
		if os.name == 'nt':
			return self.proc.kill(sig)

		pgid = os.getpgid(self.proc.pid)
		os.killpg(pgid, sig) 
Example #22
Source File: server.py    From eggnog-mapper with GNU Affero General Public License v3.0 5 votes vote down vote up
def shutdown_server():
    global MASTER, WORKER
    try:
        os.killpg(os.getpgid(MASTER.pid), signal.SIGTERM)
    except (OSError, AttributeError):
        pass
    try:
        os.killpg(os.getpgid(WORKER.pid), signal.SIGTERM)
    except (OSError, AttributeError):
        pass 
Example #23
Source File: _service_manager.py    From cotyledon with Apache License 2.0 5 votes vote down vote up
def _fast_exit(self, signo=None, frame=None,
                   reason='Caught SIGINT signal, instantaneous exiting'):
        if os.name == 'posix':
            signal.signal(signal.SIGINT, signal.SIG_IGN)
            signal.signal(signal.SIGALRM, signal.SIG_IGN)
            LOG.info(reason)
            os.killpg(0, signal.SIGINT)
        else:
            # NOTE(sileht): On windows killing the master process
            # with SIGINT kill automatically children
            LOG.info(reason)
        os._exit(1) 
Example #24
Source File: interactive.py    From screeps_console with MIT License 5 votes vote down vote up
def __del__(self):
        if self.proc:
            try:
                os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
            except:
                pass 
Example #25
Source File: cross_platform_process.py    From sublime-gulp with MIT License 5 votes vote down vote up
def kill(self):
        if sublime.platform() == "windows":
            kill_process = subprocess.Popen(['C:\\Windows\\system32\\taskkill.exe', '/F', '/T', '/PID', str(self.pid)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            kill_process.communicate()
        else:
            os.killpg(self.pid, signal.SIGTERM)
        ProcessCache.remove(self) 
Example #26
Source File: stop_record_logs_state.py    From generic_flexbe_states with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_enter(self, userdata):
		"""Upon entering the state, kill the process"""

		os.killpg(userdata.rosbag_process.pid, signal.SIGINT) 
Example #27
Source File: launcher.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def stop(self):
        self.status = "stopped"
        os.killpg(os.getpgid(self._process.pid), signal.SIGTERM)
        print(f"[Cluster {self.id}] The cluster is killed.")
        await asyncio.sleep(5) 
Example #28
Source File: tracer.py    From judge-server with GNU Affero General Public License v3.0 5 votes vote down vote up
def kill(self):
        # FIXME(quantum): this is actually a race. The process may exit before we kill it.
        # Under very unlikely circumstances, the pid could be reused and we will end up
        # killing the wrong process.
        if self.returncode is None:
            log.warning('Request the killing of process: %s', self.pid)
            try:
                os.killpg(self.pid, signal.SIGKILL)
            except OSError:
                import traceback

                traceback.print_exc()
        else:
            log.warning('Skipping the killing of process because it already exited: %s', self.pid) 
Example #29
Source File: launcher.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def kill(self):
        self.status = "stopped"
        os.killpg(os.getpgid(self._process.pid), signal.SIGTERM) 
Example #30
Source File: multigpu.py    From DDRL with Apache License 2.0 5 votes vote down vote up
def run_step(self):
        if not self.async_running:
            self.async_running = True
            for th in self.training_threads: # resume all threads
                th.resume()
        next(self.async_step_counter)

        if self.config.extra_arg['max_steps'] is not None and self.step_counter >= self.config.extra_arg['max_steps']:
            import os
            import signal
            os.killpg(os.getpgrp(), signal.SIGKILL)

            import sys
            sys.exit()
        else:
            self.step_counter += 1

        s = ("Q-debug id=dkjs, tf_queue_size {qsize}".format(qsize=self.queue_size_op.eval()))
        logger.debug(s)

        super(AsyncMultiGPUTrainer, self).run_step()

        self.main_thread_counter += 1
        elapsed_time = elapsed_time_ms(self.main_thread_timer)
        self.step_times.append(elapsed_time)
        last_k = 20
        mean_step_time = np.mean(self.step_times[-last_k:])

        self.dp_per_s = 1000.0 / mean_step_time * self.config.extra_arg['batch_size']

        #if int(self.async_step_counter.__str__()) % 100 == 0:
        import os
        s = ("[{node}]  step: {step}, step_time {step_time}, mean_step_time {mean_step_time}, it/s {it_s}".format(
             node=os.getenv("SLURMD_NODENAME", "none"),
             step=self.async_step_counter.__str__(),
             step_time=round(elapsed_time, 2),
             mean_step_time=round(mean_step_time,2),
             it_s=round(1000.0 / mean_step_time, 2)))
        logger.error(s)
        self.main_thread_timer = start_timer()