树莓派进阶之路 (033)

因为需求需要,树莓派开机需要自动运行一些代码和脚本,并且需要对网络是否正常进行监测,所以需要做带网络监测的自启动服务。

参考了一下文档:

Linux开机启动程序详解

Linux中设置服务自启动的三种方式linux服务的开机启动和运行级别linux系统的7种运行级别ubuntu下设置开机启动服务,

Ubuntu15.x /CentOS 7.x 以后 设置开机启动,添加自定义系统服务,自定义开机启动

Ubuntu14.04设置开机启动脚本如何添加自定义脚本到开机自启动linux添加开机自启动脚本示例详解linux添加开机自启动脚本示例详解 ,几种设置树莓派开机自启的方法

nohup-真正的Shell后台运行让linux服务器上的程序在后台运行

经过上面的文档:

进入配置开机启动文件:

cd /etc
sudo vim rc.local

rc.local

 1 #!/bin/sh -e
 2 #
 3 # rc.local
 4 #
 5 # This script is executed at the end of each multiuser runlevel.
 6 # Make sure that the script will "exit 0" on success or any other
 7 # value on error.
 8 #
 9 # In order to enable or disable this script just change the execution
10 # bits.
11 #
12 # By default this script does nothing.
13 
14 # Print the IP address
15 _IP=$(hostname -I) || true
16 if [ "$_IP" ]; then
17   printf "My IP address is %s
" "$_IP"
18 fi
19 
20 nohup  /etc/init.d/network_test.sh &    #后台启动自定义脚本
21 
22 exit 0  

建立自定义的网络测试脚本:

vim network_test.sh

把一下文件cp到文件中:

 1 #!/bin/bash
 2 #
 3 #检测网络链接&&ftp上传数据
 4 
 5 
 6 declare -i n=0            #在定义变量n前面加上declare -i 表示该变量为数值
 7 while [ $n -ne 1 ]        #判断
 8 do
 9         ret_code=`curl -I -s --connect-timeout 5 baidu.com -w %{http_code} | tail -n1`    #网络值
10          if [ "$ret_code" = "200" ]; then
11                 nohup /home/pi/bind &           #网络连接成功启动脚本程序脚本
12                 n=1;
13         else
14                 n=0; #失败等待
15         fi
16 done

把文件cp到rc.local脚本自定的目录:

sudo mv network_test.sh /etc/init.d

我们在/home/pi目录中建立自己的启动脚本 bind 来启动自定义的脚本。

=============================== 脚本实现方法=================================

service.sh

 1 #!/bin/bash
 2 
 3 sudo rm -r pi/
 4 sudo apt-get install git
 5 git clone https://gitee.com/jikexianfeng/pi.git
 6 cd ~/pi/service
 7 sudo mv ./rc.local /etc/rc.local
 8 sudo mv ./network_test.sh /etc/init.d/network_test.sh
 9 mv bind ~
10 cd
11 sudo rm -r pi/
12 rm service.sh
13 sudo reboot
原文地址:https://www.cnblogs.com/jikexianfeng/p/7611184.html