Notifications when process is killed

chrisallick chrisallick at gmail.com
Wed Aug 3 23:47:20 EDT 2011


On Aug 1, 5:56 am, Andrea Di Mario <anddima... at gmail.com> wrote:
> Hi, i've created a twisted server application and i want that the
> server send me a message when someone stops or kills the process.
> I want to override reactor.stop(), but do this way send me message
> when the process is stopped by a system kill?
> Could you suggest me if there's a way to do this?
>
> Thanks, regards.
>
> --
> Andrea Di Mario

This will catch Ctrl+C and a Kill PID request:

# Add SIGINT handler for killing the threads
def signal_handler(signal, frame):
	print "Received exit command."
	server.running = False
	sys.exit()

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

And this will find an destroy a process:

import os, signal

process = "websocket.py"

found = False
for line in os.popen("ps ax | grep python"):
	fields = line.split()
	pid = fields[0]
	for field in fields:
		if field.find(process) >= 0:
			print pid
			print field
			os.kill(int(pid), signal.SIGTERM)
			found = True
			break
	if found == True:
		break

if found == True:
	print "found and killed web server process."
else:
	print "could not find web server process."



More information about the Python-list mailing list