簡體   English   中英

Python檢測Linux關閉並在關閉之前運行命令

[英]Python detect linux shutdown and run a command before shutting down

是否有可能檢測並中斷linux(Ubuntu 16.04)關機信號(例如,單擊電源按鈕或電池電量耗盡)。 我有一個始終在錄制視頻的python應用程序,並且我想檢測到這種信號,因此在操作系統關閉之前我會正確關閉錄制。

當linux關閉時,所有進程都會收到SIGTERM ,如果超時后它們不會終止,則會被SIGKILL殺死。 您可以實現信號處理程序,以使用signal模塊正確關閉應用程序。 systemd (在較早的Ubuntu版本中反對upstart )在關閉時還會發送SIGHUP

為了驗證它是否確實有效,我在兩個Ubuntu VM(12.04和16.04)上嘗試了以下腳本。 系統在發出SIGKILL之前等待10s(12.04 / upstart)或90s(16.04 / systemd)。

該腳本將忽略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。

對此進行研究基本上,將具有正確名稱的腳本放入/etc/rc0.d/並執行對您的python腳本的調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM