Esempio n. 1
0
def host(app, bind_to):
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    acceptor.bind(bind_to)
    acceptor.listen(1024)

    process_info = dict(
        name='Parent',
        master_pid=os.getpid()
    )

    @atexit.register
    def on_exit():
        acceptor.close()
        print "{0} {1} has left the building.".format(process_info['name'], os.getpid())

    for i in range(30):
        @fork
        def child():
            process_info['name'] = 'Child'
            parent_pid = process_info['master_pid']

            @trap(signal.SIGINT)
            def exit_when_interrupted():
                sys.exit()

            server_name, server_port = get_server_address(acceptor)
            acceptor.settimeout(0.0)
            rlist = [acceptor]

            server = Server(app, {
                'multicor.process_name': process_info['name']
            })

            while True:
                for ready_sock in rlist:
                    try:
                        sock, client_address = ready_sock.accept()
                    except IOError as ex:
                        if ex.errno not in (errno.EAGAIN, errno.ECONNABORTED): raise
                    else:
                        # TODO: handle errors!
                        sock.settimeout(None)
                        with closing(sock):
                            WSGIRequestHandler(sock, client_address, server)

                # Quit if we see that our parent is gone.
                if os.getppid() != parent_pid: return

                try:
                    rlist, wlist, xlist = select([acceptor], [], [], 5.0)
                except IOError as ex:
                    if ex.errno == errno.EINTR:
                        rlist = [acceptor]
                    elif ex.errno == errno.EBADF:
                        return
                    else:
                        raise

        print "Forked child: {0}".format(child.pid)

    @trap(signal.SIGINT)
    def exit_parent():
        print "\nbailing"
        sys.exit()

    wait_all()
Esempio n. 2
0
for i in range(3):
    @fork
    def child():
        global name
        name = "Child"

        @trap(signal.SIGINT)
        def exit_when_interrupted():
            sys.exit()

        done = False
        while not done:
            sock, addr = acceptor.accept()
            sock.sendall("Child {0} echo> ".format(os.getpid()))
            with contextlib.closing(sock.makefile('rb')) as sock_input:
                message = sock_input.readline()
                done = message.strip().lower() == 'quit'
            sock.sendall(message)
            sock.close()
            print "Child {0} echo'd: {1}".format(os.getpid(), message.strip())

    print "Forked child: {0}".format(child.pid)

@trap(signal.SIGINT)
def exit_parent():
    print "\nbailing"
    sys.exit()

wait_all()