尝试编写一个在代码中按CTRL+ 号退出的代码时, C实现时会遇到问题,因为大多数在线帮助都涉及信号和其他可能与要求无关的内容。可以跳过此部分并提供解决方案
import signal
import time
def sigint_handler(signum, frame):
print 'Stop pressing the CTRL+C!'
signal.signal(signal.SIGINT, sigint_handler)
Run Code Online (Sandbox Code Playgroud)
目的:
按ctrl+ c应该只是退出程序
您可以在上进行try / except KeyboardInterrupt:
try:
while True:
print 1
except KeyboardInterrupt:
print "test"
Run Code Online (Sandbox Code Playgroud)
或者,如果进程本身被杀死,则将SIGTERM通过KILL命令发送一条消息:
如您所指出的,您可以定义一个处理程序: signal.signal(signal.SIGTERM, my_signal_term_handler)
这是要考虑的所有UNIX信号的列表:http : //en.wikipedia.org/wiki/Unix_signal#POSIX_signals。请注意,无法捕获SIGKILL。