套接字对象可以与Python的多处理共享吗? socket.close()似乎不起作用 [英] Can socket objects be shared with Python's multiprocessing? socket.close() does not seem to be working

查看:71
本文介绍了套接字对象可以与Python的多处理共享吗? socket.close()似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个对每个客户端使用multiprocessing.Process的服务器.在父进程中调用socket.accept(),并将连接对象作为该进程的参数给出.

I'm writing a server which uses multiprocessing.Process for each client. socket.accept() is being called in a parent process and the connection object is given as an argument to the Process.

问题是,当调用socket.close()时,套接字似乎没有关闭.在服务器上调用close()之后,客户端的recv()应该立即返回.在使用threading.Thread或仅在主线程中处理请求时就是这种情况,但是在使用多处理时,客户端的recv似乎一直挂着.

The problem is that when calling socket.close() the socket does not seem to be closing. The client's recv() should return immediately after close() has been called on the server. This is the case when using threading.Thread or just handle the requests in the main thread, however when using multiprocessing, the client's recv seem to be hanging forever.

某些来源指示套接字对象应与multiprocessing.Pipes和multiprocess.reduction共享为句柄,但不应共享似乎有所不同.

Some sources indicate that socket objects should be shared as handles with multiprocessing.Pipes and multiprocess.reduction but it does not seem to make a difference.

我在Linux 64位上使用Python 2.7.4.

I am using Python 2.7.4 on Linux 64 bit .

下面是演示此问题的示例实现.

Below are the sample implementation demonstrating this issue.

import socket
from multiprocessing import Process
#from threading import Thread as Process

s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 5001))
s.listen(5)

def process(s):
    print "accepted"
    s.close()
    print "closed"

while True:
    print "accepting"
    c, _ = s.accept()
    p = Process(target=process, args=(c,))
    p.start()
    print "started process"

client.py

import socket

s = socket.socket()
s.connect(('', 5001))
print "connected"
buf = s.recv(1024)

print "buf: '" + buf +"'"

s.close()

推荐答案

问题是套接字未在父进程中关闭.因此,它保持打开状态,并导致您所观察到的症状.

The problem is that the socket is not closed in the parent process. Therefore it remains open, and causes the symptom you are observing.

在分叉子进程以处理连接后,应立即关闭父进程的套接字副本,如下所示:

Immediately after forking off the child process to handle the connection, you should close the parent process' copy of the socket, like so:

while True:
    print "accepting"
    c, _ = s.accept()
    p = Process(target=process, args=(c,))
    p.start()
    print "started process"
    c.close()

这篇关于套接字对象可以与Python的多处理共享吗? socket.close()似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆