我有以下代码,主机名检查其IP。如果主机名不存在,则socket.gethostbyname()呼叫的超时时间约为10秒。这对我的需求来说太长了。超时一秒就足够了。因此,我用signal包装代码,期望被引发。但是,当我运行以下代码时,确实调用了处理程序,但似乎socket.gethostbyname()阻塞,因此它永远不会被取消。
我做错了什么?
import socket
import signal
def handler(signum, frame):
print('Signal handler called with signal {}.'.format(signum))
raise UserWarning("DNS timeout!")
hostname = 'some-silly-host-name-that-does-not-exist'
ip = None
try:
signal.signal(signal.SIGALRM, handler)
signal.alarm(1)
ip = socket.gethostbyname(hostname)
signal.alarm(0)
except (socket.gaierror, UserWarning) as err:
print(err)
finally:
print("IP is {}".format(ip))