Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 插座对和叉接中的FD重用_Python_Sockets - Fatal编程技术网

Python 插座对和叉接中的FD重用

Python 插座对和叉接中的FD重用,python,sockets,Python,Sockets,我试图为研究编写一个预工作服务器,我发现os.fork将重用FD编号 虽然输出是正确的,但我伤的是为什么 下面是代码和输出 #!/usr/bin/env python # encoding: utf-8 import os import socket import time def main(): for x in xrange(4): parent_sock, children_sock = socket.socketpair() #parent

我试图为研究编写一个预工作服务器,我发现os.fork将重用FD编号

虽然输出是正确的,但我伤的是为什么

下面是代码和输出

#!/usr/bin/env python
# encoding: utf-8

import os
import socket
import time

def main():


    for x in xrange(4):
        parent_sock, children_sock = socket.socketpair()
        #parent_sock.setblocking(0)
        #children_sock.setblocking(0)
        pid = os.fork()

        if pid != 0:
            print os.getpid(), "M->parent", parent_sock.fileno()
            print os.getpid(), "M->children", children_sock.fileno()
            parent_sock.send('HI %d' % pid)

        else:
            #child
            print os.getpid(), "C->parent", parent_sock.fileno()
            print os.getpid(), "C->child", children_sock.fileno()
            time.sleep(3)
            print children_sock.fileno(), children_sock.recv(4096)
            return


if __name__ == '__main__':
    main()
正如您所看到的,这只是一个正常的预处理服务器代码,我使用time.sleep禁用python销毁child_sock。 但为什么两个子进程都使用fileno 4、6,仍然得到正确答案

$python fork.py
16414 M->parent 3
16414 M->children 4
16415 C->parent 3
16415 C->child 4
16414 M->parent 5
16414 M->children 6
16416 C->parent 5
16416 C->child 6
16414 M->parent 3
16414 M->children 4
16417 C->parent 3
16417 C->child 4
16414 M->parent 5
16414 M->children 6
16418 C->parent 5
16418 C->child 6

$4 HI 16415
6 HI 16416
4 HI 16417
6 HI 16418
垃圾收集

在parent中的每次
for
迭代中,局部变量
parent\u sock
children\u sock
都指向新创建的套接字,并且以前的值不再可访问,因此Python可以选择关闭并重用旧套接字

如果您将所有套接字存储在某个位置,它会阻止Python进行垃圾收集,因此不会关闭它们,您将看到不同的数字

我的意思是:此代码可以重用一些FD编号:

for x in xrange(4):
    parent_sock, children_sock = socket.socketpair()
    print "M->parent", parent_sock.fileno()
    print "M->children", children_sock.fileno()
但该代码不能:

list_sockets = []
for x in xrange(4):
    parent_sock, children_sock = socket.socketpair()
    list_sockets.append([parent_sock, children_sock])
    print "M->parent", parent_sock.fileno()
    print "M->children", children_sock.fileno()