Search This Blog

Monday, October 5, 2015

Python Signals and IPC

What does this script do?

Creates a tcp server which listens on a port. Implements signals to ensure it automatically shutsdown after a pre-configured duration which is given through command line

Python version: 2.6

[root@host-172-17-95-7 module2]# cat signals_exercise.py
import signal, sys
from socket import *
from optparse import OptionParser

HOST = ""
PORT = 37845
ADDR = (HOST,PORT)
BUFSIZE = 4096

# Create a raw socket
serv = socket(AF_INET, SOCK_STREAM)

def option_parser():
 parser = OptionParser()
 parser.add_option('-t','--time',help="Time for server to server",action='store',type=int,\
 dest='time_to_serv')
 (options, args) = parser.parse_args()
 return options,args


def signal_handler(signum,frm):
 print "Got signal: %s" %signum
 print "Shutting down the server"
 serv.shutdown(SHUT_WR)
 print "Closing the server"
 serv.close()
 sys.exit()

def bind_server():
 print "Binding tcpServer"
 serv.bind((ADDR))
 serv.listen(100) # Listen time is greater than time_to_serv

def trigger_alarm(time_to_serv):
 print "Triggering signal"
 signal.signal(signal.SIGALRM,signal_handler)
 signal.alarm(time_to_serv)
 print "Done!"

if __name__ == '__main__':
 options, args = option_parser()
 bind_server()
 trigger_alarm(options.time_to_serv)

 while True:
 pass
[root@host-172-17-95-7 module2]# python signals_exercise.py -t 5
Binding tcpServer
Triggering signal
Done!
Got signal: 14
Shutting down the server
Closing the server
[root@host-172-17-95-7 module2]#
[root@host-172-17-95-7 module2]# netstat -nap | grep 37845
[root@host-172-17-95-7 module2]# netstat -nap | grep python

No comments:

Post a Comment