https://docs.python.org/3.5/library/os.html#fd-inheritance下关于"继承文件描述符"的文档说:
"在UNIX上,在执行新程序时,在子进程中关闭不可继承的文件描述符,其他文件描述符被继承。"
套接字的文档也说,"新创建的套接字是不可继承的。"
我刚刚用下面的代码测试了它:import socket, os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('localhost', 9999))
sock.listen(512)
sock.settimeout(1)
print("Socket inheritable?: {}".format(sock.get_inheritable()))
pid = os.fork()
if not pid: # child process
print(sock)
else:
pass
通过调用"sock.get_inheritable()"如果得到False,则表示套接字不可继承。但是子进程似乎继承了套接字描述符。
我错过了什么吗?为什么会这样呢?
感谢更新:下面是在子进程中等待接受的"server.py":
import socket, os, time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('localhost', 9999))
sock.listen(512)
sock.setblocking(True)
print("Socket inheritable?: {}".format(sock.get_inheritable()))
pid = os.fork()
if not pid: # child process
sock, addr = sock.accept()
data = sock.recv(100)
print(data.decode())
else:
while True:
time.sleep(1)
"client.py"向套接字发送"Hello":
import socket, time, select, sys
msg = "Hello".encode()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost',9999))
s.setblocking(1)
s.send(msg)
s.close()
启动server.py并运行"client.py"后,看到"server.py"的终端打印出"Hello"消息
不可继承意味着描述符是关闭的,正如引号中所说的那样。这并不意味着Python中对套接字对象的引用消失了。
更有意义的测试应该是在条件的两个分支中尝试从套接字中读取。