Python检测Linux关闭并在关闭之前运行命令
问题内容:
是否可以检测并中断linux(Ubuntu
16.04)关机信号(例如,单击电源按钮或电池电量耗尽)。我有一个始终在录制视频的python应用程序,并且我想检测到这种信号,因此在操作系统关闭之前我会正确关闭录制。
问题答案:
当linux关闭时,所有进程都会接收到,SIGTERM
并且如果它们在超时后不会终止,则会被杀死SIGKILL
。您可以实现信号处理程序,以使用该signal
模块正确关闭应用程序。systemd
(与upstart
早期的Ubuntu版本相对)(另外)SIGHUP
在关闭时发送。
为了验证这确实有效,我在两个Ubuntu VM(12.04和16.04)上尝试了以下脚本。系统在发出之前等待10s(12.04 /
upstart)或90s(16.04 / systemd)SIGKILL
。
该脚本将忽略SIGHUP
(否则也会不合时宜地终止进程),并将自从SIGTERM
信号接收到文本文件以来连续打印时间。
注意 我使用disown
(内置bash命令)从终端分离进程。
python signaltest.py &
disown
signaltest.py
import signal
import time
stopped = False
out = open('log.txt', 'w')
def stop(sig, frame):
global stopped
stopped = True
out.write('caught SIGTERM\n')
out.flush()
def ignore(sig, frsma):
out.write('ignoring signal %d\n' % sig)
out.flush()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGHUP, ignore)
while not stopped:
out.write('running\n')
out.flush()
time.sleep(1)
stop_time = time.time()
while True:
out.write('%.4fs after stop\n' % (time.time() - stop_time))
out.flush()
time.sleep(0.1)
打印到的最后一行log.txt
是:
10.1990s after stop
为12.04和
90.2448s after stop
为16.04。