我如何通过关闭标准输入文件描述符来关闭子线程?

how do i keep closing a subthread from closing the stdin file descriptor?

我写了这段代码来澄清我的问题...我不断收到 ValueError: I/O operation on closed file.

None 个子线程从标准输入读取。在我启动子线程之前,循环工作得很好......有人能告诉我如何防止文件描述符关闭吗?

import threading
from threadtest2 import Threadtest
import termios, sys, tty
import time

def getchar():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch


tt2 = Threadtest()
stop = threading.Event()

t1 = threading.Thread(target=tt2.thread1, args=[stop, ])
t2 = threading.Thread(target=tt2.thread2, args=[stop, ])

try:
    while 1:
        while not stop.isSet():
            try:
                c = getchar()
            except IOError: pass
            if c == "q":
                stop.set()
            if c == "x":
                stop.set()
                exit()
            if c == "1":
                print "starting t1"
                t1.start()
            if c == "2":
                print "starting t2"
                t2.start()
        while len(threading.enumerate()) > 1:
            print 'waiting for ' + str(len(threading.enumerate()) - 1) + ' threads to close\r'
            time.sleep(1)
        stop.clear()
        print "stop has been triggered and reset... restart"
finally:
    print "done!"

还有一些其他话题(请原谅双关语)触及了这一点,但我还没有找到直接解决它的话题,并且已经讨论了一段时间。

仅供参考,子线程只是等待设置停止并休眠...

我对你的代码做了一些小改动,运行它是独立的。以下不会在 Linux 机器上为我生成错误。你仍然看到它的错误吗?如果是这样,我很乐意改进答案 - 请提供更多有关您如何 运行 正在使用操作系统的代码的详细信息。

import threading
import termios, sys, tty
import time

def getchar():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

class Threadtest:
    def thread1(self, stop):
        stop.wait()
        print "returning from thread1"
    def thread2(self, stop):
        stop.wait()
        print "returning from thread2"

tt2 = Threadtest()
stop = threading.Event()

try:
    while 1:
        t1 = threading.Thread(target=tt2.thread1, args=[stop, ])
        t2 = threading.Thread(target=tt2.thread2, args=[stop, ])

        while not stop.isSet():
            try:
                c = getchar()
            except IOError: pass
            if c == "q":
                stop.set()
            if c == "x":
                stop.set()
                sys.exit()
            if c == "1":
                print "starting t1"
                t1.start()
            if c == "2":
                print "starting t2"
                t2.start()
        print "waiting for {} threads to close".format(threading.active_count() - 1)
        for t in [t1, t2]:
            t.join()
        stop.clear()
        print "stop has been triggered and reset... restart"
finally:
    print "done!"