使用 systemd 来管理启动项 启动序列( 六 )

你可以看到 systemd 启动了 hello.service单元,它执行了hello.sh脚本并将输出记录在日志中 。如果你能在启动阶段抓到它,你也应该能看见,systemd 信息表明了它正在启动这个脚本,另外一条信息表明了服务成功 。通过观察上面数据流中第一条 systemd 消息,你会发现 systemd 在到达基本的系统目标后很快就启动了你的服务 。
但是我想看见信息在启动阶段也被打印出来 。有一种方法可以做到:在 hello.service文件的[Service]段中加入下述行:
StandardOutput=journal+console现在 hello.service文件看起来像这样:
# Simple service unit file to use for testing# startup configurations with systemd.# By David Both# Licensed under GPL V2#[Unit]Description=My hello shell script[Service]Type=oneshotExecStart=/usr/local/bin/hello.shStandardOutput=journal+console[Install]WantedBy=multi-user.target加上这一行后,重启系统,并在启动过程中观察显示屏上滚动的数据流 。你应该在它的小方框中看到信息 。在启动序列完成后,你可以查看最近的启动日志,然后定位到你新服务的日志记录 。
修改次序现在你的服务已经可用了,你可以看看它在启动序列中哪个位置启动的,尝试下修改它 。需要牢记的是 systemd 倾向于在每个主要目标(basic.targetmulti-user.targetgraphical.**target)中并行启动尽可能多的服务和其他的单元类型 。你应该刚刚看过最近一次开机的日志记录,它应该和上面我的日志看上去类似 。
注意,systemd 在它到达到基本系统目标(basic.target)后不久就启动了你的测试服务 。这正是你在在服务单元文件的WantedBy行中指定的,所以它是对的 。在你做出修改之前,列出
/etc/systemd/system/multi-user.target.wants
目录下的内容,你会看到一个指向服务单元文件的软链接 。服务单元文件的[Install]段指定了哪一个目标会启动这个服务,执行systemctl enable hello.service命令会在适当的targets.wants路径下创建软链接 。
hello.service -> /etc/systemd/system/hello.service某些服务需要在 basic.target阶段启动,其他则没这个必要,除非系统正在启动graphical.target 。这个实验中的服务不会在basic.target期间启动 —— 假设你直到graphical.target阶段才需要它启动 。那么修改WantedBy这一行:
WantedBy=graphical.target一定要先禁用 hello.service再重新启用它,这样可以删除旧链接并且在graphical.targets.wants目录下创建一个新的链接 。我注意到如果我在修改服务需要的目标之前忘记禁用该服务,我可以运行systemctl disable命令,链接将从两个targets.wants目录中删除 。之后我只需要重新启用这个服务然后重启电脑 。
启动 graphical.target下的服务有个需要注意的地方,如果电脑启动到multi-user.target阶段,这个服务不会自动启动 。如果这个服务需要 GUI 桌面接口,这或许是你想要的,但是它同样可能不是你想要的 。
用 -o short-monotonic选项来查看graphical.targetmulti-user.target的日志,展示内核启动几秒后的日志,精度为微秒级别:
[root@testvm1 ~]# journalctl -b -o short-monotonicmulti-user.target的部分日志:
[   17.264730] testvm1.both.org systemd[1]: Starting My hello shell script...[   17.265561] testvm1.both.org systemd[1]: Starting IPv4 firewall with iptables...[   19.478468] testvm1.both.org systemd[1]: Starting LSB: Init script for live image....[   19.507359] testvm1.both.org iptables.init[844]: iptables: Applying firewall rules: [  OK  ][   19.507835] testvm1.both.org hello.sh[843]: ###############################[   19.507835] testvm1.both.org hello.sh[843]: ######### Hello World! ########[   19.507835] testvm1.both.org hello.sh[843]: ###############################[   21.482481] testvm1.both.org systemd[1]: hello.service: Succeeded.[   21.482550] testvm1.both.org smartd[856]: Opened configuration file /etc/smartmontools/smartd.conf[   21.482605] testvm1.both.org systemd[1]: Finished My hello shell script.

推荐阅读