我想知道是否有可能检测到由于 Linux 系统断电而导致的关机。(断电定义为:按复位键、按电源键、拔电源线) 如果是,怎么办?(即,如果这已经是人们可以做的事情,我应该运行哪些命令?)
我想像这样工作的方式:
这取决于您的实现,last但是如果您的系统崩溃了,您将在last输出中看到有关此效果的消息。
注意到crash线条了吗?这是由于断电或有人按下此特定系统上的电源开关造成的。
$ last
root pts/0 greeneggs.bubba. Tue May 13 22:42 - 22:43 (00:01)
reboot system boot 2.6.18-238.19.1. Tue May 13 21:47 (4+17:29)
root pts/0 greeneggs.bubba. Tue May 13 21:36 - crash (00:11)
root pts/0 greeneggs.bubba. Mon May 12 03:29 - 03:29 (00:00)
root pts/0 greeneggs.bubba. Sun May 11 16:47 - 19:41 (02:53)
root pts/0 greeneggs.bubba. Sat May 10 17:10 - 17:12 (00:01)
root pts/0 greeneggs.bubba. Sat May 10 08:35 - 08:35 (00:00)
root pts/1 greeneggs.bubba. Thu May 8 23:56 - 23:56 (00:00)
reboot system boot 2.6.18-238.19.1. Thu May 8 23:55 (9+15:21)
root pts/0 greeneggs.bubba. Thu May 8 22:39 - 22:41 (00:02)
root pts/0 greeneggs.bubba. Tue May 6 21:36 - 22:06 (00:30)
sam pts/0 byers.bubba.net Tue May 6 12:36 - 13:04 (00:28)
root pts/0 :0.0 Mon May 5 23:12 - 23:12 (00:00)
root :0 Mon May 5 23:03 - crash (3+00:51)
Run Code Online (Sandbox Code Playgroud)
我见过一个很好用的方法是,如果你有一台笔记本电脑,你可以使用命令行工具acpi来查询系统的 ACPI 接口。这将告诉您系统何时通电或电池耗尽等信息。
这是我的笔记本电脑上该命令的输出。
$ acpi -V
Battery 0: Unknown, 94%
Battery 0: design capacity 6963 mAh, last full capacity 6683 mAh = 95%
Adapter 0: on-line
Thermal 0: ok, 52.0 degrees C
Thermal 0: trip point 0 switches to mode critical at temperature 100.0 degrees C
Thermal 0: trip point 1 switches to mode passive at temperature 95.5 degrees C
Cooling 0: LCD 0 of 15
Cooling 1: Processor 0 of 10
Cooling 2: Processor 0 of 10
Cooling 3: Processor 0 of 10
Cooling 4: Processor 0 of 10
Run Code Online (Sandbox Code Playgroud)
只需检查该行的内容即可Adapter知道系统的当前状态。这可以封装到监视器中,例如,如果您想监视一组机器以查看它们是否作为一个组经历过断电。
插入
$ acpi -V | grep "Adapter"
Adapter 0: on-line
Run Code Online (Sandbox Code Playgroud)
不插电
$ acpi -V | grep "Adapter"
Adapter 0: off-line
Run Code Online (Sandbox Code Playgroud)
您可以通过在系统正确关闭或用户启动重新启动(init 0 或 6)时创建占位符文件来实现此目的。运行启动脚本(init 3 或 5)来检查文件是否存在。如果丢失,则无法正常关闭。如果该文件确实存在(即系统正常关闭或重新启动),只需删除锁定文件即可。
只需确保不要将占位符文件写入内存中安装的目录(/dev/shm、/var/run 等)或 /tmp,因为系统重新引导时这些目录将被清空。