有时候,我们想一开机就自动运行某些程序,或脚本。

解决方案:

/etc/rc.local 中添加相应的命令来执行某些程序

 

适用范围:

自动运行某些程序,或脚本,只能运行于后台在前台运行的,或前台显示的程序,是不能运行的(我尝试过,把显示窗口的程序写在里面,让开机就自动运行,发现整个程序运行不的)

 

实现步骤:

1、建立rc-local.service文件

sudo gedit /etc/systemd/system/rc-local.service

 

2、将下列内容复制进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

 

3、创建文件rc.local  

sudo gedit /etc/rc.local

 

4、将下列内容复制进rc.local文件

#!/bin/sh -e
#
# 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.
echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log
exit 0

 

5、给rc.local加上权限

sudo chmod +x /etc/rc.local

 

6、启用服务

sudo systemctl enable rc-local

说明:正常启用服务不会报错的(没有任何提示)。

 

7、启动服务并检查状态

sudo systemctl start rc-local.service
sudo systemctl status rc-local.service

 说明:正常开启服务不会报错的(没有红色的Fail.........出现,说明能正常启动)。

 

8、重启并检查test.log文件

cat /usr/local/test.log  

如果能看到内容,说明设置成功,你就可以通过编辑rc.local文件来设置启动脚本了。

 

案例1:

编写/etc/rc.local

#!/bin/sh -e
#
# 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.
#echo "看到这行字,说明添加自启动脚本成功。" > /pu/13.c



echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log
cd /home/pu/pu_student/壁障/壁障+串口通讯+完善_haha_单片机 && ./test

exit 0

解释:cd 壁障+串口通讯+完善_haha_单片机 && ./test

进入目录:壁障+串口通讯+完善_haha_单片机  ,并且执行 test

test 是用 C语言编写,然后编译好的可执行程序

保存退出!

 

关机重启,用命令top 查看test 是否运行

ubuntu-16 开机启动程序 rc.local方式

看到开机就自动执行程序 test ,恭喜你,成功了。

 

 

相关文章: