字典破坏文件描述符

时间:2019-02-25 02:42:34

标签: python python-3.x

我有一种奇怪的情况,即当存储在字典中时文件描述符被破坏了。

#!/usr/bin/env python3

import threading
import time

class test:
    id = -1
    fd = {}
    fd_nodict = None
    thread = None

    def __init__(self, id, filename1, filename2, filename3):   

        self.id = id
        self.fd["one"] = open(filename1,"r")
        self.fd["two"] = open(filename2,"w")

        self.fd_nodict = open(filename3,"r")

        print( "init id: %d" % self.id)
        print( "openning fd[one] => %d" % self.fd["one"].fileno() )
        print( "openning fd[two] => %d" % self.fd["two"].fileno() )
        print( "openning fd_nodict => %d" % self.fd_nodict.fileno() )

        self.thread = threading.Thread(target=self.loop)
        self.thread.start()

    def loop(self):

        while True:
            time.sleep(5)
            print( "update id: %d" % self.id)
            print( "fd[one] => %d" % self.fd["one"].fileno() )
            print( "fd[two] => %d" % self.fd["two"].fileno() )
            print( "fd_nodict => %d" % self.fd_nodict.fileno() )

t1= test(1,"/sys/class/gpio/gpio224/value","/sys/class/gpio/gpio225/value","/sys/class/gpio/gpio226/value")
t2= test(2,"/sys/class/gpio/gpio227/value","/sys/class/gpio/gpio228/value","/sys/class/gpio/gpio229/value")

运行此命令时,输出为:

root@mx7:~# python3 dict_fd_test.py 
init id: 1
openning fd[one] => 3
openning fd[two] => 4
openning fd_nodict => 5
init id: 2
openning fd[one] => 6
openning fd[two] => 3
openning fd_nodict => 4
update id: 1
fd[one] => 6
fd[two] => 3
fd_nodict => 5
update id: 2
fd[one] => 6
fd[two] => 3
fd_nodict => 4

因此,我创建了两个对象,并分别打开3个文件(在本例中为某些gpios)。然后,我创建一个线程,并从胎面检查文件句柄号。字典中存储的文件描述符被破坏了(您可以看到它们最初是3,4,然后是6,3(这似乎已经很糟糕了),但是在线程回调之后,它们都是6,3

但是fd_nodict看起来不错。因此,问题似乎仅在于将FD存储在字典中。有什么想法吗?

0 个答案:

没有答案