我使用了定时器signal.setitimer,想要在5s后退出程序,但是没有成功
这是我的代码:
from signal import setitimer, signal, SIGALRM, ITIMER_REAL, SIGKILL
import os
if __name__ == '__main__':
def _exit(*args):
print('Timeout & Exit!!!')
os.kill(os.getpid(), SIGKILL)
signal(SIGALRM, _exit)
setitimer(ITIMER_REAL, 5)
os.system('ping 127.0.0.1')
setitimer(ITIMER_REAL, 0)
这是运行的结果:
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.022 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.017 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.011 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.011 ms
64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.011 ms
64 bytes from 127.0.0.1: icmp_seq=6 ttl=64 time=0.011 ms
64 bytes from 127.0.0.1: icmp_seq=7 ttl=64 time=0.011 ms
64 bytes from 127.0.0.1: icmp_seq=8 ttl=64 time=0.010 ms
64 bytes from 127.0.0.1: icmp_seq=9 ttl=64 time=0.012 ms
64 bytes from 127.0.0.1: icmp_seq=10 ttl=64 time=0.011 ms
64 bytes from 127.0.0.1: icmp_seq=11 ttl=64 time=0.011 ms
64 bytes from 127.0.0.1: icmp_seq=12 ttl=64 time=0.011 ms
64 bytes from 127.0.0.1: icmp_seq=13 ttl=64 time=0.011 ms
如果我将os.system('ping 127.0.0.1')替换成while True:pass, 程序会在5s后自动退出,谁能帮忙解释下呢?