4. 添加系统服务到根文件系统构建脚本¶
除了直接在启动的板卡上创建Systemd服务,我们也可以在根文件系统的构建脚本中添加。
此处以Debian镜像构建脚本为例。
4.1. 编写脚本¶
打开LubanCat-SDK,并在debian/overlay/etc/init.d目录下创建hello.sh脚本
1 2 3 4 5 6 7 | #!/bin/bash
while true
do
echo Hello Lubancat >> /tmp/hello.log
sleep 3
done
|
该脚本实现的功能是每隔3秒就打印“Hello Lubancat”字符串到/tmp/hello.log文件中。 编写好后记得赋予hello.sh可执行权限。
sudo chmod 0755 hello.sh
4.2. 创建配置文件¶
在debian/overlay/usr/lib/systemd/system/目录下创建一个hello.service配置文件,内容如下。
1 2 3 4 5 6 7 8 9 10 | [Unit]
Description = hello daemon
[Service]
ExecStart = /etc/init.d/hello.sh
Restart = always
Type = simple
[Install]
WantedBy = multi-user.target
|
其中ExecStart字段定义了hello.service服务的自启动脚本为/etc/init.d/hello.sh, 当我们使能了hello.service开机自启功能,在开机后便会执行/etc/init.d/hello.sh。 Restart = always表示指进程或服务意外故障的时候可以自动重启的模式。 Type = simple为默认的,可以不填。
4.3. 使能hello.service开机自启功能¶
我们还需要在/etc/systemd/system/的multi-user.target.wants 目录下创建指向/usr/lib/systemd/system/hello.service的软连接, 来使hello.service加入multi-user.target,在这个组里的所有服务,都将开机启动
我们来到LubanCat-SDK的debian/overlay/etc/systemd/system/multi-user.target.wants目录下,使用ln命令创建软连接。
1 2 3 4 5 | # 进入ulti-user.target.wants目录
cd debian/overlay/etc/systemd/system/multi-user.target.wants
# 创建软连接
ln -s /usr/lib/systemd/system/hello.service hello.service
|
修改完成后我们重新构建根文件系统,等待。
系统镜像构建完成后重新烧录板卡,启动系统后输入“sudo systemctl status hello”命令即可看到hello.service处于运行状态。
sudo systemctl status hello
cat /tmp/hello.log