Python detect linux shutdown and run a command before shutting down

前端 未结 2 1525
失恋的感觉
失恋的感觉 2021-01-13 08:39

Is it possible to detect and interrupt linux (Ubuntu 16.04) shutdown signal (e.g. power button clicked or runs out of battery). I have a python application that is always re

相关标签:
2条回答
  • 2021-01-13 08:52

    When linux is shut down, all processes receive SIGTERM and if they won't terminate after some timeout they are killed with SIGKILL. You can implement a signal handler to properly shutdown your application using the signal module. systemd (opposed to upstart in earlier Ubuntu verions) additionally sends SIGHUP on shutdown.

    To verfiy that this actually works, I tried the following script on two Ubuntu VMs (12.04 and 16.04). The system waits for 10s (12.04/upstart) or 90s (16.04/systemd) before issuing SIGKILL.

    The script ignores SIGHUP (which would otherwise also kill the process ungracefully) and will continuously print the time since the SIGTERM signal has been received to a text file.

    Note I used disown (built-in bash command) to detach the process from the terminal.

    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)
    

    The last line printed into log.txt was:

    10.1990s after stop
    

    for 12.04 and

    90.2448s after stop
    

    for 16.04.

    0 讨论(0)
  • 2021-01-13 08:59

    Look into this Basically, put a script in /etc/rc0.d/ with the right name and execute a call to you python script.

    0 讨论(0)
提交回复
热议问题