步骤:
"""
fork多进程并发
"""
import signal
from socket import *
import os
# Windows上无法运行fork
# from multiprocessing import Process
# 全局变量
ADDR = ('0.0.0.0', 8888)
# 客户端处理函数
def handle(c):
while True:
data = c.recv(1024)
if not data:
break
print(data.decode())
c.send(b'ok')
c.close()
# 创建监听套接字
s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(ADDR)
s.listen(3)
# 处理僵尸进程
# signal.signal(signal.SIGCHLD, signal.SIG_IGN)
# 循环等待客户端连接
print('Listen the port 8888...')
while True:
try:
c, addr = s.accept()
print('Connect from', addr)
except KeyboardInterrupt:
s.close()
os._exit(0) # 人为希望服务队退出
except Exception as e:
print(e)
continue
# 创建子进程处理连接的客户端请求
pid = os.fork()
if pid == 0:
s.close() # 子进程中没有需要用s
# 处理客户端请求
handle(c)
os._exit(0)
else:
c.close() # 父进程中没有需要用c