大网数据广告活动
服务器运维问答

Get systemd actual state

· 52CE 我爱测

How can we know if systemd has finished to boot the system ? I don't want to execute on cron job if the system is actually on boot process because of missing network connectivity. My script launched by cron would have a test on t…

问题原文

原帖链接 · Dom · CC BY-SA 4.0

How can we know if systemd has finished to boot the system ?

I don't want to execute on cron job if the system is actually on boot process because of missing network connectivity. My script launched by cron would have a test on top, and it exits if the booting process is not finished like

#!/bin/sh
$STATE=`HERE ADD THE MISSING PART`
if [ $STATE != "active" ]; then
  exit
fi
# Actions to do on next cron after booting

If it can also provide me the information about shutting down process, as the problem can be the same..;

I was doing this with SystemV with runlevel command, but Systemd do not change the runlevel at end of boot.

Thanks

已采纳解答

原帖链接 · Lacek · CC BY-SA 4.0

You can check the target you need to be active in order for your script to run. For example, in order for the network to be accessible, you need to check the network-online.target (systemctl check will return 0 if the checked unit is active)

The target systemd tries to reach is its "default" target, which can be queried by systemctl get-default. If that target is online, the system has finished booting (so you can issue systemctl status $(systemctl get-default) to check whether the boot process has finished)

Edit: If you want to monitor only the current state of the system, and you aren't interested in targets (i.e. you want to run your command only when everything is up and running), it is better to use the systemctl is-system-running command. It will output running is everything is fine, or degraded if the system is up but some of the services have failed (which may or may not indicate an error). The other states would indicate that your script shouldn't run. As a side note, it's usually better to check return values instead of parsing the text output, but the manpage doesn't specify return values, only says that anything other than "running" results of a nonzero exit code, so it might be safer to parse the output text.

See the manpage of systemctl for the possible output values.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-08-09)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。