fork 기반 다 중 프로 세 스 네트워크 병행

서버
"""
    fork        
"""
#    
from socket import *
import os,sys
import signal

def handle(c):
    print("   :",c.getpeername())
    while True:
        data = c.recv(1024)
        if not data:
            break
        print(data.decode())
        c.send(b'OK')


#        
HOST = "0.0.0.0"
PORT = 8888
ADDR = (HOST,PORT)
#      
s = socket()  # tcp   
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()
    except KeyboardInterrupt:
        sys.exit("     ")
    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

좋은 웹페이지 즐겨찾기