Python os.kill() Examples

The following are code examples for showing how to use os.kill(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: alfred-yubikey-otp   Author: robertoriv   File: background.py    MIT License 6 votes vote down vote up
def kill(name, sig=signal.SIGTERM):
    """Send a signal to job ``name`` via :func:`os.kill`.

    .. versionadded:: 1.29

    Args:
        name (str): Name of the job
        sig (int, optional): Signal to send (default: SIGTERM)

    Returns:
        bool: `False` if job isn't running, `True` if signal was sent.
    """
    pid = _job_pid(name)
    if pid is None:
        return False

    os.kill(pid, sig)
    return True 
Example 2
Project: pyblish-win   Author: pyblish   File: test_break.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testInterruptCaught(self):
        default_handler = signal.getsignal(signal.SIGINT)

        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            self.assertTrue(result.shouldStop)

        try:
            test(result)
        except KeyboardInterrupt:
            self.fail("KeyboardInterrupt not handled")
        self.assertTrue(result.breakCaught) 
Example 3
Project: pyblish-win   Author: pyblish   File: test_break.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testSecondInterrupt(self):
        # Can't use skipIf decorator because the signal handler may have
        # been changed after defining this method.
        if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
            self.skipTest("test requires SIGINT to not be ignored")
        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            self.assertTrue(result.shouldStop)
            os.kill(pid, signal.SIGINT)
            self.fail("Second KeyboardInterrupt not raised")

        try:
            test(result)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("Second KeyboardInterrupt not raised")
        self.assertTrue(result.breakCaught) 
Example 4
Project: pyblish-win   Author: pyblish   File: test_break.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testTwoResults(self):
        unittest.installHandler()

        result = unittest.TestResult()
        unittest.registerResult(result)
        new_handler = signal.getsignal(signal.SIGINT)

        result2 = unittest.TestResult()
        unittest.registerResult(result2)
        self.assertEqual(signal.getsignal(signal.SIGINT), new_handler)

        result3 = unittest.TestResult()

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)

        try:
            test(result)
        except KeyboardInterrupt:
            self.fail("KeyboardInterrupt not handled")

        self.assertTrue(result.shouldStop)
        self.assertTrue(result2.shouldStop)
        self.assertFalse(result3.shouldStop) 
Example 5
Project: pyblish-win   Author: pyblish   File: test_break.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testHandlerReplacedButCalled(self):
        # Can't use skipIf decorator because the signal handler may have
        # been changed after defining this method.
        if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
            self.skipTest("test requires SIGINT to not be ignored")
        # If our handler has been replaced (is no longer installed) but is
        # called by the *new* handler, then it isn't safe to delay the
        # SIGINT and we should immediately delegate to the default handler
        unittest.installHandler()

        handler = signal.getsignal(signal.SIGINT)
        def new_handler(frame, signum):
            handler(frame, signum)
        signal.signal(signal.SIGINT, new_handler)

        try:
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("replaced but delegated handler doesn't raise interrupt") 
Example 6
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _send_signal(self, sig):
            if self.pid == 0:
                # see "man 2 kill"
                raise ValueError(
                    "preventing sending signal to process with PID 0 as it "
                    "would affect every process in the process group of the "
                    "calling process (os.getpid()) instead of PID 0")
            try:
                os.kill(self.pid, sig)
            except OSError as err:
                if err.errno == errno.ESRCH:
                    self._gone = True
                    raise NoSuchProcess(self.pid, self._name)
                if err.errno == errno.EPERM:
                    raise AccessDenied(self.pid, self._name)
                raise 
Example 7
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def pid_exists(pid):
    """Return True if given PID exists in the current process list.
    This is faster than doing "pid in psutil.pids()" and
    should be preferred.
    """
    if pid < 0:
        return False
    elif pid == 0 and _POSIX:
        # On POSIX we use os.kill() to determine PID existence.
        # According to "man 2 kill" PID 0 has a special meaning
        # though: it refers to <<every process in the process
        # group of the calling process>> and that is not we want
        # to do here.
        return pid in pids()
    else:
        return _psplatform.pid_exists(pid) 
Example 8
Project: pyblish-win   Author: pyblish   File: test_multiprocessing.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_ignore(self):
        conn, child_conn = multiprocessing.Pipe()
        try:
            p = multiprocessing.Process(target=self._test_ignore,
                                        args=(child_conn,))
            p.daemon = True
            p.start()
            child_conn.close()
            self.assertEqual(conn.recv(), 'ready')
            time.sleep(0.1)
            os.kill(p.pid, signal.SIGUSR1)
            time.sleep(0.1)
            conn.send(1234)
            self.assertEqual(conn.recv(), 1234)
            time.sleep(0.1)
            os.kill(p.pid, signal.SIGUSR1)
            self.assertEqual(conn.recv_bytes(), b'x'*(1024*1024))
            time.sleep(0.1)
            p.join()
        finally:
            conn.close() 
Example 9
Project: pyblish-win   Author: pyblish   File: test_multiprocessing.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_ignore_listener(self):
        conn, child_conn = multiprocessing.Pipe()
        try:
            p = multiprocessing.Process(target=self._test_ignore_listener,
                                        args=(child_conn,))
            p.daemon = True
            p.start()
            child_conn.close()
            address = conn.recv()
            time.sleep(0.1)
            os.kill(p.pid, signal.SIGUSR1)
            time.sleep(0.1)
            client = multiprocessing.connection.Client(address)
            self.assertEqual(client.recv(), 'welcome')
            p.join()
        finally:
            conn.close()

#
#
# 
Example 10
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: background.py    MIT License 6 votes vote down vote up
def kill(name, sig=signal.SIGTERM):
    """Send a signal to job ``name`` via :func:`os.kill`.

    .. versionadded:: 1.29

    Args:
        name (str): Name of the job
        sig (int, optional): Signal to send (default: SIGTERM)

    Returns:
        bool: `False` if job isn't running, `True` if signal was sent.
    """
    pid = _job_pid(name)
    if pid is None:
        return False

    os.kill(pid, sig)
    return True 
Example 11
Project: AutoDL   Author: tanguofu   File: reloader_helpers.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def kill_process_children_unix(pid):
    """Find and kill child process of a process (maximum two level).

    :param pid: PID of process (process ID)
    :return: Nothing
    """
    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:
            os.kill(int(_pid), signal.SIGTERM) 
Example 12
Project: flasky   Author: RoseOu   File: pidfile.py    MIT License 6 votes vote down vote up
def validate(self):
        """ Validate pidfile and make it stale if needed"""
        if not self.fname:
            return
        try:
            with open(self.fname, "r") as f:
                try:
                    wpid = int(f.read())
                except ValueError:
                    return

                try:
                    os.kill(wpid, 0)
                    return wpid
                except OSError as e:
                    if e.args[0] == errno.ESRCH:
                        return
                    raise
        except IOError as e:
            if e.args[0] == errno.ENOENT:
                return
            raise 
Example 13
Project: flasky   Author: RoseOu   File: arbiter.py    MIT License 6 votes vote down vote up
def kill_worker(self, pid, sig):
        """\
        Kill a worker

        :attr pid: int, worker pid
        :attr sig: `signal.SIG*` value
         """
        try:
            os.kill(pid, sig)
        except OSError as e:
            if e.errno == errno.ESRCH:
                try:
                    worker = self.WORKERS.pop(pid)
                    worker.tmp.close()
                    self.cfg.worker_exit(self, worker)
                    return
                except (KeyError, OSError):
                    return
            raise 
Example 14
Project: myhoard   Author: aiven   File: myhoard.py    Apache License 2.0 6 votes vote down vote up
def _restart_process(self, *, mysqld_options):
        # When not using systemd and we haven't started mysqld (during current invocation of the daemon)
        # start by determining current pid (if any) of the process so that we can kill it before starting.
        if self.mysqld_pid is None:
            self.mysqld_pid = detect_running_process_id(" ".join(self.config["start_command"])) or -1
        if self.mysqld_pid and self.mysqld_pid > 0:
            self.log.info("Terminating running mysqld process %s", self.mysqld_pid)
            os.kill(self.mysqld_pid, signal.SIGTERM)
            os.waitpid(self.mysqld_pid, 0)
            self.log.info("Process %s exited", self.mysqld_pid)
            self.mysqld_pid = -1

        full_command = self.config["start_command"] + mysqld_options
        self.log.info("Starting process %r", full_command)
        proc = subprocess.Popen(full_command, env={"MYSQLD_OPTS": " ".join(mysqld_options)})
        self.mysqld_pid = proc.pid
        self.log.info("Process %r started, pid %s", full_command, proc.pid) 
Example 15
Project: alfred-urban-dictionary   Author: xilopaint   File: background.py    MIT License 6 votes vote down vote up
def kill(name, sig=signal.SIGTERM):
    """Send a signal to job ``name`` via :func:`os.kill`.

    .. versionadded:: 1.29

    Args:
        name (str): Name of the job
        sig (int, optional): Signal to send (default: SIGTERM)

    Returns:
        bool: `False` if job isn't running, `True` if signal was sent.
    """
    pid = _job_pid(name)
    if pid is None:
        return False

    os.kill(pid, sig)
    return True 
Example 16
Project: PathDump   Author: PathDump   File: tcpmon.py    Apache License 2.0 6 votes vote down vote up
def monitor_retransmit():
    global proc

    with proc.stdout:
        for line in iter (proc.stdout.readline, b''):
            if stop_flag:
                break

            tokens = line.split()
            if len(tokens) < 5 or (tokens[2] == '-:-' and tokens[4] == '-:-') \
                    or tokens[0] == "TIME":
                continue

            key = tokens[1] + ':' + tokens[3] + ':6'

            mon_lock.acquire()
            if key not in mon_flows:
                print "updating mon_flows", key
                mon_flows.update ({key: 1})
            mon_lock.release()

    os.kill (proc.pid, signal.SIGTERM)
    proc.wait() # wait for the subprocess to exit
    proc = None 
Example 17
Project: Paradrop   Author: ParadropLabs   File: command.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, pid, parent=None):
        """
        Create a kill command

        The pid argument can either be a real pid (e.g. kill 12345) or a path
        to a file containing the pid.

        If the pid is coming from a file, it will be resolved at the time that
        execute is called.  Before that time, the command will be stored
        internally as ["kill", "/path/to/file"].  This is not a real command,
        but it is meaningful if you print the command object.
        """
        # This will not be a valid command if pid is a file path.
        command = ["kill", pid]

        super(KillCommand, self).__init__(command, parent)

        # Is it a numeric pid or a path to a pid file?
        try:
            self.pid = int(pid)
            self.fromFile = False
        except ValueError:
            self.pid = pid
            self.fromFile = True 
Example 18
Project: Paradrop   Author: ParadropLabs   File: command.py    Apache License 2.0 6 votes vote down vote up
def execute(self):
        pid = self.getPid()

        if pid is None:
            self.result = 0
            return True

        try:
            retval = kill(pid)
            self.result = 0
            out.info('Command "kill {}" returned {}\n'.format(pid, retval))
        except Exception as e:
            out.info('Command "kill {}" raised exception {}\n'.format(pid, e))
            self.result = e

        return (self.result == 0) 
Example 19
Project: factotum   Author: Denubis   File: factotum.py    GNU General Public License v3.0 5 votes vote down vote up
def stop():
	"""Shortcut for factorio stop."""
	try:
		FACTORIOPATH = getFactorioPath()
		with open('/tmp/factorio.pid', 'r') as pidfile:
			pid = int(pidfile.read().strip())
			os.kill(pid, signal.SIGINT)
		print("SIGINT sent")
		time.sleep(10)
	except FileNotFoundError:
		print("Cannot find pid. Factorio has not been started.")		
	print(subprocess.check_output(['tail', '-13', '%s/factorio-current.log'%FACTORIOPATH]).decode("unicode_escape")) 
Example 20
Project: fs_image   Author: facebookincubator   File: test_unshare.py    MIT License 5 votes vote down vote up
def _kill_keepalive(self, unshare: Unshare):
        # We can kill the inner keepalive `cat` since it runs w/ our UID
        # Since it's an `init` of a PID namespace, we must use SIGKILL.
        cat_pid = int(re.match(
            '^/proc/([0-9]+)/ns/',
            next(iter(unshare._namespace_to_file.values())).name,
        ).group(1))
        print('Sending SIGKILL to', cat_pid)
        os.kill(cat_pid, signal.SIGKILL) 
Example 21
Project: alfred-yubikey-otp   Author: robertoriv   File: background.py    MIT License 5 votes vote down vote up
def _process_exists(pid):
    """Check if a process with PID ``pid`` exists.

    :param pid: PID to check
    :type pid: ``int``
    :returns: ``True`` if process exists, else ``False``
    :rtype: ``Boolean``

    """
    try:
        os.kill(pid, 0)
    except OSError:  # not running
        return False
    return True 
Example 22
Project: pyblish-win   Author: pyblish   File: test_break.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testInstallHandler(self):
        default_handler = signal.getsignal(signal.SIGINT)
        unittest.installHandler()
        self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)

        try:
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
        except KeyboardInterrupt:
            self.fail("KeyboardInterrupt not handled")

        self.assertTrue(unittest.signals._interrupt_handler.called) 
Example 23
Project: pyblish-win   Author: pyblish   File: _psposix.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if pid == 0:
        # According to "man 2 kill" PID 0 has a special meaning:
        # it refers to <<every process in the process group of the
        # calling process>> so we don't want to go any further.
        # If we get here it means this UNIX platform *does* have
        # a process with id 0.
        return True
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            # ESRCH == No such process
            return False
        elif err.errno == errno.EPERM:
            # EPERM clearly means there's a process to deny access to
            return True
        else:
            # According to "man 2 kill" possible error values are
            # (EINVAL, EPERM, ESRCH) therefore we should never get
            # here. If we do let's be explicit in considering this
            # an error.
            raise err
    else:
        return True 
Example 24
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def as_dict(self, attrs=None, ad_value=None):
        """Utility method returning process information as a
        hashable dictionary.

        If 'attrs' is specified it must be a list of strings
        reflecting available Process class' attribute names
        (e.g. ['cpu_times', 'name']) else all public (read
        only) attributes are assumed.

        'ad_value' is the value which gets assigned in case
        AccessDenied or ZombieProcess exception is raised when
        retrieving that particular process information.
        """
        excluded_names = set(
            ['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
             'is_running', 'as_dict', 'parent', 'children', 'rlimit'])
        retdict = dict()
        ls = set(attrs or [x for x in dir(self)])
        for name in ls:
            if name.startswith('_'):
                continue
            if name in excluded_names:
                continue
            try:
                attr = getattr(self, name)
                if callable(attr):
                    ret = attr()
                else:
                    ret = attr
            except (AccessDenied, ZombieProcess):
                ret = ad_value
            except NotImplementedError:
                # in case of not implemented functionality (may happen
                # on old or exotic systems) we want to crash only if
                # the user explicitly asked for that particular attr
                if attrs:
                    raise
                continue
            retdict[name] = ret
        return retdict 
Example 25
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def send_signal(self, sig):
        """Send a signal to process pre-emptively checking whether
        PID has been reused (see signal module constants) .
        On Windows only SIGTERM is valid and is treated as an alias
        for kill().
        """
        if _POSIX:
            self._send_signal(sig)
        else:
            if sig == signal.SIGTERM:
                self._proc.kill()
            else:
                raise ValueError("only SIGTERM is supported on Windows") 
Example 26
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def terminate(self):
        """Terminate the process with SIGTERM pre-emptively checking
        whether PID has been reused.
        On Windows this is an alias for kill().
        """
        if _POSIX:
            self._send_signal(signal.SIGTERM)
        else:
            self._proc.kill() 
Example 27
Project: pyblish-win   Author: pyblish   File: subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            elif sig == signal.CTRL_C_EVENT:
                os.kill(self.pid, signal.CTRL_C_EVENT)
            elif sig == signal.CTRL_BREAK_EVENT:
                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
            else:
                raise ValueError("Unsupported signal: {}".format(sig)) 
Example 28
Project: pyblish-win   Author: pyblish   File: subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            os.kill(self.pid, sig) 
Example 29
Project: pyblish-win   Author: pyblish   File: subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def kill(self):
            """Kill the process with SIGKILL
            """
            self.send_signal(signal.SIGKILL) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_signal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_main(self):
        # This function spawns a child process to insulate the main
        # test-running process from all the signals. It then
        # communicates with that child process over a pipe and
        # re-raises information about any exceptions the child
        # raises. The real work happens in self.run_test().
        os_done_r, os_done_w = os.pipe()
        with closing(os.fdopen(os_done_r)) as done_r, \
             closing(os.fdopen(os_done_w, 'w')) as done_w:
            child = os.fork()
            if child == 0:
                # In the child process; run the test and report results
                # through the pipe.
                try:
                    done_r.close()
                    # Have to close done_w again here because
                    # exit_subprocess() will skip the enclosing with block.
                    with closing(done_w):
                        try:
                            self.run_test()
                        except:
                            pickle.dump(traceback.format_exc(), done_w)
                        else:
                            pickle.dump(None, done_w)
                except:
                    print 'Uh oh, raised from pickle.'
                    traceback.print_exc()
                finally:
                    exit_subprocess()

            done_w.close()
            # Block for up to MAX_DURATION seconds for the test to finish.
            r, w, x = select.select([done_r], [], [], self.MAX_DURATION)
            if done_r in r:
                tb = pickle.load(done_r)
                if tb:
                    self.fail(tb)
            else:
                os.kill(child, signal.SIGKILL)
                self.fail('Test deadlocked after %d seconds.' %
                          self.MAX_DURATION) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_process_awareness(self):
        # ensure that the random source differs between
        # child and parent.
        read_fd, write_fd = os.pipe()
        pid = None
        try:
            pid = os.fork()
            if not pid:
                os.close(read_fd)
                os.write(write_fd, next(self.r).encode("ascii"))
                os.close(write_fd)
                # bypass the normal exit handlers- leave those to
                # the parent.
                os._exit(0)
            parent_value = next(self.r)
            child_value = os.read(read_fd, len(parent_value)).decode("ascii")
        finally:
            if pid:
                # best effort to ensure the process can't bleed out
                # via any bugs above
                try:
                    os.kill(pid, signal.SIGKILL)
                except EnvironmentError:
                    pass
            os.close(read_fd)
            os.close(write_fd)
        self.assertNotEqual(child_value, parent_value) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_kill(self):
        p = self._kill_process('kill')
        _, stderr = p.communicate()
        self.assertStderrEqual(stderr, '')
        self.assertEqual(p.wait(), -signal.SIGKILL) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_kill_dead(self):
        # Killing a dead process
        self._kill_dead_process('kill') 
Example 34
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_kill(self):
        self._kill_process('kill') 
Example 35
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_kill_dead(self):
        self._kill_dead_process('kill') 
Example 36
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_kill_int(self):
        # os.kill on Windows can take an int which gets set as the exit code
        self._kill(100) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _kill_with_event(self, event, name):
        tagname = "test_os_%s" % uuid.uuid1()
        m = mmap.mmap(-1, 1, tagname)
        m[0] = '0'
        # Run a script which has console control handling enabled.
        proc = subprocess.Popen([sys.executable,
                   os.path.join(os.path.dirname(__file__),
                                "win_console_handler.py"), tagname],
                   creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
        # Let the interpreter startup before we send signals. See #3137.
        count, max = 0, 20
        while count < max and proc.poll() is None:
            if m[0] == '1':
                break
            time.sleep(0.5)
            count += 1
        else:
            self.fail("Subprocess didn't finish initialization")
        os.kill(proc.pid, event)
        # proc.send_signal(event) could also be done here.
        # Allow time for the signal to be passed and the process to exit.
        time.sleep(0.5)
        if not proc.poll():
            # Forcefully kill the process if we weren't able to signal it.
            os.kill(proc.pid, signal.SIGINT)
            self.fail("subprocess did not stop on {}".format(name)) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_threadsignals.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def send_signals():
    os.kill(process_pid, signal.SIGUSR1)
    os.kill(process_pid, signal.SIGUSR2)
    signalled_all.release() 
Example 39
Project: pyblish-win   Author: pyblish   File: test_fork1.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_import_lock_fork(self):
        import_started = threading.Event()
        fake_module_name = "fake test module"
        partial_module = "partial"
        complete_module = "complete"
        def importer():
            imp.acquire_lock()
            sys.modules[fake_module_name] = partial_module
            import_started.set()
            time.sleep(0.01) # Give the other thread time to try and acquire.
            sys.modules[fake_module_name] = complete_module
            imp.release_lock()
        t = threading.Thread(target=importer)
        t.start()
        import_started.wait()
        pid = os.fork()
        try:
            if not pid:
                m = __import__(fake_module_name)
                if m == complete_module:
                    os._exit(0)
                else:
                    os._exit(1)
            else:
                t.join()
                # Exitcode 1 means the child got a partial module (bad.) No
                # exitcode (but a hang, which manifests as 'got pid 0')
                # means the child deadlocked (also bad.)
                self.wait_impl(pid)
        finally:
            try:
                os.kill(pid, signal.SIGKILL)
            except OSError:
                pass 
Example 40
Project: pyblish-win   Author: pyblish   File: forking.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def terminate(self):
            if self.returncode is None:
                try:
                    os.kill(self.pid, signal.SIGTERM)
                except OSError, e:
                    if self.wait(timeout=0.1) is None:
                        raise 
Example 41
Project: pyblish-win   Author: pyblish   File: PyShell.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def close(self):
        "Extend EditorWindow.close()"
        if self.executing:
            response = tkMessageBox.askokcancel(
                "Kill?",
                "The program is still running!\n Do you want to kill it?",
                default="ok",
                parent=self.text)
            if response is False:
                return "cancel"
        self.stop_readline()
        self.canceled = True
        self.closing = True
        return EditorWindow.close(self) 
Example 42
Project: arm_now   Author: nongiach   File: download.py    MIT License 5 votes vote down vote up
def get_link_filetype(link):
    if ".cpio" in link or ".ext2" in link or "rootfs" in link:
        return "rootfs"
    elif "dtb" in link:
        return "dtb"
    elif "Image" in link or "vmlinux" in link or "linux.bin" in link:
        return "kernel"
    print("ERROR: I don't know this kind of file {}".format(link), file=sys.stderr)
    # os.kill(0, 9)
    return None 
Example 43
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: background.py    MIT License 5 votes vote down vote up
def _process_exists(pid):
    """Check if a process with PID ``pid`` exists.

    :param pid: PID to check
    :type pid: ``int``
    :returns: ``True`` if process exists, else ``False``
    :rtype: ``Boolean``

    """
    try:
        os.kill(pid, 0)
    except OSError:  # not running
        return False
    return True 
Example 44
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: serving.py    Apache License 2.0 5 votes vote down vote up
def initiate_shutdown(self):
        """A horrible, horrible way to kill the server for Python 2.6 and
        later.  It's the best we can do.
        """
        # Windows does not provide SIGKILL, go with SIGTERM then.
        sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
        # reloader active
        if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
            os.kill(os.getpid(), sig)
        # python 2.7
        self.server._BaseServer__shutdown_request = True
        # python 2.6
        self.server._BaseServer__serving = False 
Example 45
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: serving.py    Apache License 2.0 5 votes vote down vote up
def initiate_shutdown(self):
        """A horrible, horrible way to kill the server for Python 2.6 and
        later.  It's the best we can do.
        """
        # Windows does not provide SIGKILL, go with SIGTERM then.
        sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
        # reloader active
        if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
            os.kill(os.getpid(), sig)
        # python 2.7
        self.server._BaseServer__shutdown_request = True
        # python 2.6
        self.server._BaseServer__serving = False 
Example 46
Project: kvmd   Author: pikvm   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def __run_system_task(self, method: Callable, *args: Any) -> None:
        async def wrapper() -> None:
            try:
                await method(*args)
                raise RuntimeError(f"Dead system task: {method.__name__}"
                                   f"({', '.join(getattr(arg, '__name__', str(arg)) for arg in args)})")
            except asyncio.CancelledError:
                pass
            except Exception:
                get_logger().exception("Unhandled exception, killing myself ...")
                os.kill(os.getpid(), signal.SIGTERM)
        self.__system_tasks.append(asyncio.create_task(wrapper())) 
Example 47
Project: shelter   Author: seznam   File: runserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sigusr1_handler(self, unused_signum, unused_frame):
        """
        Handle SIGUSR1 signal. Call function which is defined in the
        **settings.SIGUSR1_HANDLER**. If main process, forward the
        signal to all child processes.
        """
        for process in self.processes:
            if process.pid and os.getpid() == self.main_pid:
                try:
                    os.kill(process.pid, signal.SIGUSR1)
                except ProcessLookupError:
                    pass
        if self._sigusr1_handler_func is not None:
            self._sigusr1_handler_func(self.context) 
Example 48
Project: iSDX   Author: sdn-ixp   File: faucet_util.py    Apache License 2.0 5 votes vote down vote up
def kill_on_exception(logname):
    """decorator to ensure functions will kill ryu when an unhandled exception
    occurs"""
    def _koe(func):
        @wraps(func)
        def __koe(*args, **kwargs):
            try:
                func(*args, **kwargs)
            except:
                logging.getLogger(logname).exception(
                    "Unhandled exception, killing RYU")
                logging.shutdown()
                os.kill(os.getpid(), signal.SIGKILL)
        return __koe
    return _koe 
Example 49
Project: speedrun   Author: inferno-pytorch   File: resource.py    Apache License 2.0 5 votes vote down vote up
def is_alive(pid):
        """Checks if a process with PID `pid` is alive."""
        try:
            os.kill(pid, 0)
        except OSError:
            return False
        else:
            return True 
Example 50
Project: flasky   Author: RoseOu   File: serving.py    MIT License 5 votes vote down vote up
def initiate_shutdown(self):
        """A horrible, horrible way to kill the server for Python 2.6 and
        later.  It's the best we can do.
        """
        # Windows does not provide SIGKILL, go with SIGTERM then.
        sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
        # reloader active
        if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
            os.kill(os.getpid(), sig)
        # python 2.7
        self.server._BaseServer__shutdown_request = True
        # python 2.6
        self.server._BaseServer__serving = False