硬件:HD-RK3576-PI
软件:Linux6.1+Ubuntu22.04
程序自启动
1. 编写测试脚本
编写一个测试脚本用以测试。例如,想要上电后调试串口自动规律性间打印10条信息,在/home目录下编写测试脚本文件test.sh:
# /home/test.sh
#!/bin/sh
CYCLES=10
while [ $CYCLES -gt 0 ]
do
echo "倒计时 $CYCLES" > /dev/ttyFIQ0
sleep .5
CYCLES=$((CYCLES - 1))
done
并给予可执行权限:
chmod +x /home/test.sh
2. 自启动脚本
/etc/rc.local脚本是文件系统中自带的一个自启脚本,可以在该脚本末尾添加开机自启动的程序。将测试脚本文件添加到/etc/rc.local文件末尾:
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# Generate the SSH keys if non-existent
if [ ! -f /etc/ssh/ssh_host_rsa_key ]
then
# else ssh service start in dpkg-reconfigure will fail
export DEBIAN_FRONTEND=noninteractive
systemctl stop ssh.socket||true
dpkg-reconfigure openssh-server
fi
/home/test.sh &
exit 0
重新上电后,可以看到调试串口自动规律性间打印10条信息。
3. systemd自启动服务
systemd 是一个新的系统和服务管理器,它已经成为大多数 Linux 发行版的默认系统。要在Ubuntu/Debian中使用 systemd 设置自启动脚本,可以执行以下步骤:
首先,编写一个自启动脚本,例如 /lib/systemd/system/myscript.service,该脚本应该以 [Unit] 开头,然后是 Description 和 After 项。在 [Service] 部分,你应该定义你要执行的命令或脚本。以下是一个示例:
[Unit]
Description=My Script Service
After=multi-user.target
[Service]
Type=simple
ExecStart=/home/test.sh
[Install]
WantedBy=multi-user.target
然后,运行以下命令:
systemctl daemon-reload
systemctl enable myscript.service
这将在系统启动时自动执行 /home/test.sh 脚本。如果你要删除该自启动脚本,可以执行以下命令:
systemctl disable myscript.service
rm /etc/systemd/system/myscript.service
systemctl daemon-reload
从自启命令打印信息可以看出,设置服务自启的本质是创建该服务的软连接,所以设置服务自启还可以执行如下命令:
ln -s /lib/systemd/system/myscript.service /etc/systmd/system/multi-user.target.want/myscript.service
4. 桌面系统方式
在桌面登录用户的家目录下创建启动文件:
# 以root用户为例
mkdir /home/root/.config/autostart
# 创建配置文件
vim /home/root/.config/autostart/test.desktop
在test.desktop文件中添加以下内容:
[Desktop Entry]
Type=Application
Exec=/home/test.sh
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=user app
Comment=user app test
该配置文件的内容说明如下:
- Type=Application:指定类型为应用程序。
- Exec=/home/test.sh:指定要执行的命令或脚本的路径。
- Hidden=false:不隐藏该自启动项。
- NoDisplay=false:在桌面环境的启动器中显示该自启动项。
- X-GNOME-Autostart-enabled=true:启用桌面环境下的自启动功能。
- Name=user app:给自启动项指定一个名称。
- Comment=user app test:自启动项的注释,描述其在登录时启动的作用。
通过这个配置文件,当用户登录桌面环境时,系统会自动执行/home/test.sh脚本并启动相应的应用程序。