openwrt通过脚本实现应用开机自启
需求分析
通过编写一个C语言程序,自动的将任意程序添加到openWrt的启动项,实现程序开机自启
主要思路(实现开机自启的脚本)
主要参考文献
-
创建脚本
initConfig.sh
并添加可执行权限:chmod +x /yourfile/initConfig.sh
-
initConfig
脚本的主要内容如下#/bin/sh #filePath=$2; fileName=$1 # fileName=$1 #touch这个语句是否可以不需要,先建好 #https://www.cnblogs.com/sunyubo/archive/2011/10/17/2282047.html #判断文件是否存在(这步应该是可要可不要,因为 echo 的 > 会自动创建文件 if [ ! -f "/etc/config/myservice" ]; then touch /etc/config/myservice fi #这里应该不需要使用-e来强制S换行 echo "config myservice 'hello'"> /etc/config/myservice echo ' option fileName '$fileName''>>/etc/config/myservice # echo ' option filePath '$filePath''>>/etc/config/myservice
-
这个脚本的主要作用是 让
bootWithSystem.sh
脚本更加个性化,定制化。 -
最终这个
initConfig.sh
脚本执行结果是:创建myservice 配置文件
-
- 成功向
/etc/config/myservice
中写入数据。
具体/etc/config/myservice
的含义可以去开头那个连接中去查看。
-
编写
bootWithSystem.sh
脚本
bootWithSystem.sh
脚本中的内容编写完成后应保存到/etc/init.d/myservice
或者 也可以直接
vi /etc/init.d/myservice
,然后将脚本内容复制到myservice
中-
脚本的主要内容如下:
脚本必须以
#!/bin/sh /etc/rc.common
开头。需要用到这两个文件夹下提供的一些函数和解释器#!/bin/sh /etc/rc.common #官网解释,使用USR_PROCD flag是为了使用新的版本(翻译的可能不准确) USE_PROCD=1 #START 标识啥时候开始,STOP标识啥时候结束 START=95 STOP=01 #https://openwrt.org/docs/guide-developer/procd-init-script-example #设置配置文件 CONFIGURATION=myservice #这些函数的用途参考:https://openwrt.org/docs/guide-developer/procd-init-scripts start_service() { # Reading config #读取配置文件 config_load "${CONFIGURATION}" local fileName # local filePath #’hello'中后的fileName字段,并保存到本地变量 fileName. config_get fileName hello fileName # config_get path hello filePath echo service $fileName start procd_open_instance # pass config to script on start procd_set_param command $fileName procd_set_param file /etc/config/myservice ##stdout stderr 用与配合 logread -f 命令输出相关的信息。 procd_set_param stdout 1 procd_set_param stderr 1 procd_close_instance } stop_service() { echo service $fileName stop } #这里用reload_service()可能更好,因为restart使旧版本中的 restart() { stop start }
-
当
initconfig.sh
执行后,创建/etc/config/myservice
后,bootWithSystem.sh
会从/etc/config/myservice
中自动获取fileName
的值。 -
执行
/etc/init.d/myservice enable /etc/init.d/myservice start #enable 设置开机自启,会在/etc/rc.d 这个文件夹中创建一个类似 S** 软连接 (** 是START设置的值) #start 用于启动服务
-
执行
ps
命令,就可以看到该进程已经执行。
-
执行
logread -f
查看输出
-