user10503628
user10503628

Reputation:

Kill a python process from another process

I need to be able to kill a python process from another process. Here is an example of how I'm doing it now:

In the 'main' process:

# Write the ProcessID to tmp file
with open('/tmp/%s' % self.query_identifier, 'w') as f: 
    f.write(str(os.getpid()))

try:
    cursor.execute('''very long query''')
except Exception:
    do_some_other_stuff()
    raise ConnectionError("There was an error completing this process")

And in the other process which 'kills' that process, I have:

pid = int(open('/tmp/%s' % self.query_identifier).read())
os.kill(pid, signal.SIGKILL)

This works great. However, this entirely terminates the python process, and so it doesn't ever get to the except block of code. What would be a better way to do the above? For example, so that I can do the "kill" operation from another separate process without terminating the python program.

Upvotes: 1

Views: 732

Answers (1)

DYZ
DYZ

Reputation: 57033

The worker program:

import signal

# Define and register a signal handler
def handler(signum, frame):
    raise IOError("Quitting on {}".format(signum))

signal.signal(signal.SIGINT, handler)

try:
    while(True): # Imitate a long and winding road
        pass
except IOError:
    print("I've been killed!")

The supervisor program:

import os, signal
os.kill(pid, signal.SIGINT)

Upvotes: 1

Related Questions