码迷,mamicode.com
首页 > 编程语言 > 详细

PYTHON多进程并发WEB服务器(利用LINUX的FORK)

时间:2015-11-25 18:46:51      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

 

这个又牛X 一点点。。

这还不涉及IO,如果调用GEVENT之类作异步IO或非阻塞IO,那就大框架都有啦。。

#####################################################################
# Iterative server - webserver3a.py                                 #
#                                                                   #
# Tested with Python 2.7.9 & Python 3.4 on Ubuntu 14.04 & Mac OS X  #
#####################################################################
import socket
import time
import os
import signal
import errno
 
SERVER_ADDRESS = (HOST, PORT) = ‘‘, 8888
REQUEST_QUEUE_SIZE = 5

def grim_reaper(signum, frame):
    while True:
    try:
        pid, status = os.waitpid(-1, os.WNOHANG)
    except OSError:
        return
    if pid == 0:
        return
    print (Child {pid} terminated with status {status}
    .format(pid=pid, status=status))
 
def handle_request(client_connection):
    request = client_connection.recv(1024)
    print(Child PID: {pid}. Parent PID {ppid}.format(
        pid=os.getpid(),
        ppid=os.getppid(),
        )
          )
    print(request.decode())
    http_response = b"""
        HTTP/1.1 200 OK
 
        Hello, Python WSGI!
        """
    client_connection.sendall(http_response)
    time.sleep(6)
 
def serve_forever():
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listen_socket.bind(SERVER_ADDRESS)
    listen_socket.listen(REQUEST_QUEUE_SIZE)
    print(Serving HTTP on port {port} ....format(port=PORT))
    print(Parent PID (PPID): {pid}.format(pid=os.getpid()))
 
    signal.signal(signal.SIGCHLD, grim_reaper)
    while True:
    try:
        client_connection, client_address = listen_socket.accept()
    except IOError as e:
        code, msg = e.args
        if code == errno.EINTR:
        continue
        else:
        raise
        pid = os.fork()
        if pid == 0:
            listen_socket.close()
            handle_request(client_connection)
            client_connection.close()
            os._exit(0)
        else:
            client_connection.close()
 
if __name__ == __main__:
    serve_forever()

技术分享

PYTHON多进程并发WEB服务器(利用LINUX的FORK)

标签:

原文地址:http://www.cnblogs.com/aguncn/p/4995141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!