openWRT中用户的应用程序如需要开机自启动的话,就需要编写开机自启动。openWRT的中procd是应用程序托管线程,如果用户应用程序宕掉,procd会自动重启服务,一般都采用procd托管的方式。
一、openWRT启动流程
openWRT 是一款基于主线linux路由功能的操作系统,系统启动流程:
(1). uboot 引导
(2). 启动内核
(3). 预初始化 /etc/preinit操作系统启动环境初始化
(4). busybox应用启动shell环境的初始化,/sbin/init 。
(5). /etc/inittab 启动console
(6). /etc/init.d/rcS 路由系统boot 启动procd、ubus等系统级服务
(7). /etc/rc.d/S* 路由系统相关应用的初始化,至此路由器运行起来。
用户应用程序、属于路由系统的一个应用,因此启动脚本需要在 第 7 步的时候运行,系统的服务和相关组件都已经运行正常后,这样避免用户程序相关依赖未启动导致程序运行异常。
二、制作应用程序自启动脚本
本文分享随镜像打包的应用程序service制作过程,也是自启动脚本。应用程序启动脚本service存放位置 /etc/init.d/ 路径下,系统运行后会自动建立软连接到 /etc/rc.d/$* 文件。
如下样例,文件名:monitor_inet
#!/bin/sh /etc/rc.common #脚本解析器注释
START=85 #启动分类号,号码越大启动越靠后
STOP=15 #关机分类号,号码越小启动越早
#PROCD=1 #应用程序procd托管开关
start() { #启动函数入口,
echo " monitor-inet startup ... "
res=`ps |grep "*monitor_inet" | grep /bin/sh `
if [ -n "${res}" ];then
echo "monitor_inet existence exiting.." > /dev/console
return 0
else
./etc/monitor_inet.sh & #用户编写的脚本
return 1
fi
}
stop() { #关闭函数入口
pid=`ps |grep monitor_inet |grep /bin/sh | awk '{print $1}'`
if [ -n "${pid}" ];then
kill ${pid}
fi
return 0
}
restart() { #重启应用函数入口
echo " monitor-inet don,t restart command "
return 0
}
该脚本在镜像中存放的位置 package/base_file/file/etc/init.d/monitor_inet 路径下;系统运行后会搜索 /etc/init.d/ 文件夹下文件,自动建立软件连接文件,以此样例,系统建立的软链接:/etc/rc.d/S85monitor_inet 软链接文件,S + 85 + monitor_inet, 85就是系统更加脚本中的 START=85 的值、加上文件生成的软链接。
用户在shell中,可通过如下方式启动
# /etc/init.d/monitor_inet start 启动脚本
# /etc/init.d/monitor_inet stop 关闭脚本
系统会根据用户输入命令执行相应的脚本,此样例中运行的是脚本。
注:应用APP的启动service脚本制作与此样例还不相同。