1

我有一个程序可以通过选择阻止读取,但我希望它通过发送 SIGINT 信号优雅地返回。并使用处理程序处理该信号。不幸的是,块程序不会从 select 系统调用返回,而是接收 SIGINT 并中断。任何人都可以帮助我找出问题所在吗?多谢。

import select
import socket
import signal

class Test(object):
    def __init__(self):
        self._read, self._write = socket.socketpair()

    def wait(self):
        readable = [self._read.fileno()]
        return select.select(readable, [], readable)

    def wakeup(self):
        self._write.send('1')


t = Test()

def handler(signum, frame):
    t.wakeup()


signal.signal(signal.SIGINT, handler)

if __name__ == '__main__':
    print t.wait()
    print 'over.'
4

1 回答 1

0

您误解了程序的行为:它确实从 select 系统调用返回,但是您必须处理错误“系统调用中断”。

import errno
import select
import socket
import signal

class Test(object):
    def __init__(self):
        self._read, self._write = socket.socketpair()

    def wait(self):
        readable = [self._read.fileno()]
        try: 
         return select.select(readable, [], readable)
        except select.error as e:
         if e.args[0] == errno.EINTR:
                return
         else:
                pass

    def wakeup(self):
        self._write.send('1')


t = Test()

def handler(signum, frame):
    t.wakeup()


signal.signal(signal.SIGINT, handler)

if __name__ == '__main__':
    print t.wait()
    print 'over.'
于 2013-05-29T07:12:00.340 回答