# L-33 MCS 275 Mon 5 Apr 2010 : clockforkserver.py # Illustration of a forking server. # Each requests spawns a process. # The server will send the time to clients. import os, sys from socket import * from time import ctime, sleep hostname = '' port = 12091 buffer = 25 server_address = (hostname,port) server = socket(AF_INET, SOCK_STREAM) server.bind(server_address) server.listen(5) # allow 5 connections active_processes = [] def kill_processes(): """ kills handler processes """ while len(active_processes) > 0: pid = active_processes.pop(0) print '-> killing process %d' % pid os.system('kill -9 %d' % pid) def handle_client(s): """ handling a client via the socket s """ print "client is blocked for ten seconds ..." sleep(10) print "handling a client ..." while True: data = s.recv(buffer) if not data: break print 'received \"' + data + '\" from client' now = ctime() print 'sending \"' + now + '\" to client' s.send(now) s.close() os._exit(0) def dispatcher(): """ listen for connecting clients """ try: print 'press ctrl c to stop server' while True: client, address = server.accept() print 'server connected at', address child_pid = os.fork() if child_pid == 0: handle_client(client) else: print 'appending PID', child_pid active_processes.append(child_pid) except: print 'ctrl c pressed, closing server' print 'active processes :', active_processes kill_processes() server.close() dispatcher()