运行环境
- 系统:Ubuntu20
- ROS:foxy
添加服务脚本
$ sudo vi /etc/systemd/system/rc-local.service
内容如下:
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99
[Install]
WantedBy=multi-user.target
编写启动脚本
注意:需要使用&符号,使用后台运行,避免阻塞
$ sudo vi /etc/rc.local
内容如下:
#!/bin/sh -e
## rc.local
bash /opt/vehicle/rosrun.sh &
注意:
编写完成后不要忘记赋予权限
$ sudo chmod 777 /etc/rc.local
编写业务脚本
$ cd /opt/vehicle
$ sudo vi rosrun.sh
内容如下:
#! /bin/sh
# 我们需要在业务脚本中先指定ROS的日志文件夹,并赋予权限,不然会运行ros程序失败
export ROS_LOG_DIR=/opt/vehicle/logs
# 激活ros的环境
. /opt/ros/foxy/setup.sh
# 激活我们自己编写的ros程序的环境
. /opt/vehicle/package/setup.sh
# 检查我们的程序是否启动
PIDS=`ps -ef | grep "ros2 run ros_cli ros_node" | grep -v grep | awk '{print $2}'`
if [ "$PIDS" != "" ]; then
echo "ros_cli is running!!!!!!!"
else
# 如果程序没有启动,需要先把程序启动
ros2 run ros_cli ros_cli_node > /opt/vehicle/test.log
fi
注意:
编写完成后不要忘记赋予权限
$ sudo chmod 777 rosrun.sh
激活服务
$ systemctl enable rc-local.service
启动服务
$ systemctl start rc-local.service
重启系统
$ sudo reboot
检查服务是否运行
$ systemctl status rc-local
结果如下:
● rc-local.service - /etc/rc.local Compatibility
Loaded: loaded (/etc/systemd/system/rc-local.service; enabled; vendor preset: enabled)
Drop-In: /usr/lib/systemd/system/rc-local.service.d
└─debian.conf
Active: active (running) since Tue 2021-07-20 09:09:44 CST; 32min ago
Process: 570244 ExecStart=/etc/rc.local start (code=exited, status=0/SUCCESS)
Main PID: 570245 (bash)
Tasks: 14 (limit: 9440)
Memory: 21.8M
CGroup: /system.slice/rc-local.service
├─570245 bash /opt/vehicle/rosrun.sh