Skip to content

开机自启配置 ​

本文介绍如何在 Rhino Pi IQ9N 的 Ubuntu 系统上配置应用开机自动启动。

方式对比 ​

方式适用场景特点
systemd 服务后台服务、长期运行的程序支持自动重启、日志管理,推荐方式
crontab简单脚本配置简单,不适合长时间运行的服务
rc.local一次性启动脚本需要手动创建并赋予可执行权限

使用 systemd 配置(推荐) ​

  1. 创建服务文件:
bash
sudo nano /etc/systemd/system/myapp.service
  1. 写入以下内容:
ini
[Unit]
Description=My Application
After=network.target

[Service]
Type=simple
User=aidlux
WorkingDirectory=/home/aidlux/myapp
ExecStart=/home/aidlux/myapp/run.sh
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
  1. 重新加载配置并启用服务:
bash
sudo systemctl daemon-reload
sudo systemctl enable myapp.service
sudo systemctl start myapp.service
  1. 查看服务状态与日志:
bash
sudo systemctl status myapp.service
journalctl -u myapp.service -f

使用 crontab 配置 ​

cron 服务在 IQ9N 上默认已启用。编辑当前用户的定时任务:

bash
crontab -e

在文件中添加任务,例如开机时执行一次脚本:

text
@reboot /home/aidlux/myapp/run.sh

查看当前已配置的任务:

bash
crontab -l

crontab 适合执行简单脚本或定时任务;长时间运行的服务仍建议使用 systemd 方式。

使用 rc.local 配置 ​

系统已预置 rc-local.service。该服务为 static 类型,无需(也不能)执行 systemctl enable;当 /etc/rc.local 存在且具有可执行权限时,systemd 会在开机时自动运行它。

  1. 创建 /etc/rc.local:
bash
sudo nano /etc/rc.local
  1. 写入以下内容:
bash
#!/bin/sh
/home/aidlux/myapp/run.sh &
exit 0
  1. 赋予可执行权限:
bash
sudo chmod +x /etc/rc.local
  1. 配置完成后重启生效。也可不重启直接验证:
bash
sudo systemctl start rc-local
sudo systemctl status rc-local

常见问题 ​

  • 服务未启动:使用 journalctl -u <服务名> 查看失败原因。
  • 脚本无执行权限:执行 chmod +x <脚本路径>。
  • 路径错误:ExecStart 中必须使用绝对路径。
  • rc.local 未生效:确认 /etc/rc.local 已存在且带有可执行权限(ls -l /etc/rc.local),赋权后重启系统。