擅长:python、mysql、java
<p>您可以设置一个信号警报,它会在超时时中断您的通话:</p>
<p><a href="http://docs.python.org/library/signal.html" rel="nofollow">http://docs.python.org/library/signal.html</a></p>
<pre><code>signal.alarm(1) # 1 second
my_blocking_call()
signal.alarm(0)
</code></pre>
<p>如果要确保不会破坏应用程序,也可以设置信号处理程序:</p>
<pre><code>def my_handler(signum, frame):
pass
signal.signal(signal.SIGALRM, my_handler)
</code></pre>
<p><strong>编辑:</strong>
这段代码怎么了?这不应中止您的应用程序:</p>
<pre><code>import signal, time
def handler(signum, frame):
print "Timed-out"
def foo():
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
# This open() may hang indefinitely
time.sleep(5)
signal.alarm(0) # Disable the alarm
foo()
print "hallo"
</code></pre>
<p>问题是:</p>
<ol>
<li><p>SIGALRM的默认处理程序是中止应用程序,如果设置了处理程序,则它将不再停止应用程序。</p></li>
<li><p>接收信号通常会中断系统调用(然后取消阻止应用程序)</p></li>
</ol>