首页 > 代码库 > Socket_Fork
Socket_Fork
1 #!/usr/bin/env python
2 #coding=utf-8
3
4 #完整的多进程服务器模型
5 import os,sys
6 from socket import socket,AF_INET,SOCK_STREAM,SOL_SOCKET,SO_REUSEADDR
7 def reaping():
8 while 1:
9 try:
10 deadprocess = os.waitpid(-1,WNOHANG)
11 if not deadprocess[0]:break
12 except:
13 print "\033[31;1mNo Zombie Process!!!\033[0m"
14 break
15 ‘‘‘没有遇到except,有僵尸进程!!‘‘‘
16 print "\033[32;1mZombie Process: %s is reaped!!!\033[0m"
17
18
19
20 def socket_server(host,port):
21 s = socket(AF_INET,SOCK_STREAM)
22 s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
23 s.bind((host,port))
24 s.listen(5)
25 return s
26
27
28 def client_handler(c_socket):
29 while True:
30 data = http://www.mamicode.com/c_socket.recv(1024)
31 print "Recv From:%s, data:[%s]" %(c_socket.getpeername()[0],data.strip())
32 ACK = "Server ACK,data:[%s],data_length:[%s]\n" %(data.strip(),len(data))
33 c_socket.send(ACK)
34 if not data or data.strip()=="quit":
35 break
36
37 c_socket.close()
38 os._exit(0)
39
40
41 #Main
42 Host = "0.0.0.0"
43 Port = 12345
44 server = socket_server(Host,Port)
45
46 print "\033[31;1mServer is waiting for the connection from client...\033[0m"
47 while True:
48 try:
49 sock,addr = server.accept()
50 except KeyboardInterrupt:
51 print "Server Ending ...."
52 sys.exit()
53 except:
54 print "Error occured"
55 sys.exit()
56 #Before generate new process, scanning zombie process
57 reaping()
58 pid = os.fork()
59 if pid:
60 """parent process,must close the client socket"""
61 sock.close()
62 continue
63 else:
64 """child process,must close the server socket"""
65 server.close()
66 print "\033[32;1mClient:[%s:%s] is connected!!\033[0m" %(addr[0],addr[1])
67 client_handler(sock)
Socket_Fork
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。