这是我可以想象的最小代码,没有错误处理,优雅的退出等。
#!/usr/bin/env python3.5
import multiprocessing, socket, traceback
from multiprocessing import reduction
def loop(pipe):
while True:
try:
c = socket.fromfd(reduction.recv_handle(pipe), socket.AF_INET, socket.SOCK_STREAM)
c.sendall('HTTP/1.1 200 OK\r\nContent-Length: 6\r\nContent-Type: text/plain\r\n\r\nhello\n'.encode())
c.shutdown(socket.SHUT_WR)
c.close()
except: print(traceback.format_exc())
if __name__ == '__main__':
pipe_recv, pipe_send = multiprocessing.Pipe()
proc = multiprocessing.Process(target=loop, args=(pipe_recv,))
proc.start()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('localhost', 9000))
s.listen()
while True:
conn, addr = s.accept()
reduction.send_handle(pipe_send, conn.fileno(), proc.pid)
我可以curl
:
curl -v http://localhost:9000/
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9000 (#0)
> GET / HTTP/1.1
> Host: localhost:9000
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Length: 6
< Content-Type: text/plain
<
hello
* Connection #0 to host localhost left intact
当我有一个或几个循环卷曲时,它工作得很好,但是如果我创建了许多客户端&#39;或者简单地使用apache基准测试,例如,脚本崩溃:
Traceback (most recent call last):
File "/tmp/this-is-my-script", line 8, in loop
c = socket.fromfd(reduction.recv_handle(pipe), socket.AF_INET, socket.SOCK_STREAM)
File "/usr/lib/python3.5/multiprocessing/reduction.py", line 181, in recv_handle
return recvfds(s, 1)[0]
File "/usr/lib/python3.5/multiprocessing/reduction.py", line 160, in recvfds
len(ancdata))
RuntimeError: received 0 items of ancdata
我花了很多时间试图理解这一点,没有运气。所以我放弃并提出这个问题。 reduction
中甚至没有记录3.5
模块。这是否意味着我不应该使用它?
如果不是 - 我没有看到在进程之间共享套接字的任何其他可能性,有没有?
如果是的话 - 我想念的是什么?
答案 0 :(得分:0)
最后!
socket.socket()
。我的代码基于this gist,不确定python2,但是在3.5中它定义导致不需要的套接字重复创建,而这反过来又保留在TIME_WAIT中,如果直接调用def fromfd(fd, family, type, proto=0):
nfd = dup(fd)
return socket(family, type, proto, nfd)
可以避免这种情况。fromfd()来源:
close()
此外,无条件关闭子进程中的套接字导致apache基准挂起。如果没有-c
,它可以正常运行。
所以最终版本如下。它实际上不是多处理的,因此它会使#!/usr/bin/env python3.5
import multiprocessing, socket, traceback
from multiprocessing import reduction
def loop(pipe_recv):
while True:
try:
conn = socket.socket(fileno=reduction.recv_handle(pipe_recv))
conn.sendall('HTTP/1.0 200 OK\r\nContent-Length: 6\r\nContent-Type: text/plain\r\n\r\nhello\n'.encode())
conn.shutdown(socket.SHUT_WR)
except: print(traceback.format_exc())
if __name__ == '__main__':
pipe_recv, pipe_send = multiprocessing.Pipe()
proc = multiprocessing.Process(target=loop, args=(pipe_recv,))
proc.start()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('localhost', 9000))
s.listen(100)
while True:
conn, addr = s.accept()
reduction.send_handle(pipe_send, conn.fileno(), proc.pid)
conn.close()
参数的apache基准测试失败。但这超出了问题的范围。
YAML::Load