How to detect pending system shutdown on Linux?

前端 未结 9 1091
死守一世寂寞
死守一世寂寞 2020-12-05 14:37

I am working on an application where I need to detect a system shutdown. However, I have not found any reliable way get a notification on this event.

I know that o

9条回答
  •  情书的邮戳
    2020-12-05 15:15

    Its a little bit of a hack but if the server is running systemd if you can run

    /bin/systemctl list-jobs shutdown.target

    ... it will report ...

    JOB UNIT            TYPE  STATE
    755 shutdown.target start waiting     <---- existence means shutting down
    
    1 jobs listed.
    

    ... if the server is shutting down or rebooting ( hint: there's a reboot.target if you want to look specifically for that )

    You will get No jobs running. if its not being shutdown.

    You have to parse the output which is a bit messy as the systemctl doesnt return a different exit code for the two results. But it does seem reasonably reliable. You will need to watch out for a format change in the messages if you update the system however.

提交回复
热议问题