程序在OS关机时需要做善后处理,那么就要判断系统是否是在reboot或者关机,Centos6.5可以通过runlevel命令查询到当前运行级别,重启时变为6,关机时变为0. Centos7废弃了runlevel的这一套,那么怎么判断呢?
1. 判断方法:
当 systemctl list-units --type target 命令同时查询到如下reboot和shutdown两个输出时,表示正在reboot
reboot.target loaded inactive dead start Reboot
shutdown.target loaded inactive dead start Shutdown
如果只能查到shutdown而没有reboot,则是在关机。
2. 原理分析
Centos7采用target方式管理系统,Centos6.5那种按照runlevel来区分OS运行级别的方式已被废弃。新旧对应关系如下:
from:
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/sect-Managing_Services_with_systemd-Targets.html#tabl-Managing_Services_with_systemd-Targets-Runlevels
Table 9.6. Comparison of SysV Runlevels with systemd Targets
Runlevel |
Target Units |
Description |
0 |
runlevel0.target , poweroff.target |
Shut down and power off the system. |
1 |
runlevel1.target , rescue.target |
Set up a rescue shell. |
2 |
runlevel2.target , multi-user.target |
Set up a non-graphical multi-user system. |
3 |
runlevel3.target , multi-user.target |
Set up a non-graphical multi-user system. |
4 |
runlevel4.target , multi-user.target |
Set up a non-graphical multi-user system. |
5 |
runlevel5.target , graphical.target |
Set up a graphical multi-user system. |
6 |
runlevel6.target , reboot.target |
Shut down and reboot the system. |
3. reboot时,查询命令完整输出。
systemctl list-units --type target
UNIT LOAD ACTIVE SUB JOB DESCRIPTION
basic.target loaded active active stop Basic System
cryptsetup.target loaded active active stop Encrypted Volumes
final.target loaded inactive dead start Final Step
local-fs-pre.target loaded active active stop Local File Systems (Pre)
local-fs.target loaded active active stop Local File Systems
network.target loaded active active stop Network
paths.target loaded active active stop Paths
reboot.target loaded inactive dead start Reboot
shutdown.target loaded inactive dead start Shutdown
slices.target loaded active active stop Slices
sockets.target loaded active active stop Sockets
swap.target loaded active active stop Swap
sysinit.target loaded active active stop System Initialization
timers.target loaded active active stop Timers
umount.target loaded inactive dead start Unmount All Filesystems
LOAD = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB = The low-level unit activation state, values depend on unit type.
JOB = Pending job for the unit.