OpenWrt的开机启动服务(init scripts)

参考 https://wiki.openwrt.org/doc/techref/initscripts

以一个简单的例子来说明

#!/bin/sh /etc/rc.common
# Example script
# Copyright (C) 2007 OpenWrt.org
 
START=10
STOP=15
 
start() {        
        echo start
        # commands to launch application
}                 
 
stop() {          
        echo stop
        # commands to kill application 
}

第一行shebang #! 使用 /bin/sh /etc/rc.common 作为脚本解释器并在执行脚本前调用 main 和检查脚本

公用的 init script 方法有

start   # 启动服务
stop    # 停止服务
restart # 重启服务
reload  # 重新载入配置文件, 如果失败则重启
enable  # 启用开机自启动
disable  # 禁用开机自启动

脚本中 start() 和 stop() 是必须的

启动顺序

START= 和 STOP= 决定脚本启动时的次序. 启动时init.d会根据文件名顺序, 自动执行在/etc/rc.d中找到的脚本. 初始化脚本可以作为/etc/init.d/下文件的软链放置在/etc/rc.d/. enable 和 disable 可以自动帮你创建对应的带序号的软链.

这个例子中START=10 会被链接到 /etc/rc.d/S10example, 启动时执行在START=9之后, 在START=11之前. 而STOP=15会被链接到 /etc/rc.d/K15example, 执行在STOP=14之后, 在STOP=16之前. 同一个启动数字的, 按字母顺序启动.

脚本中的 boot()

当存在boot()方法时, 系统启动时会调用boot()而不是start()

boot() {
    echo boot
    # commands to run on boot
}

你可以使用EXTRA_COMMANDS和EXTRA_HELP设置自定义的服务方法

EXTRA_COMMANDS="custom"
EXTRA_HELP="        custom  Help for the custom command"
 
custom() {
    echo "custom command"
    # do your custom stuff
}

多个自定义方法的添加

EXTRA_COMMANDS="custom1 custom2 custom3"
EXTRA_HELP=<<EOF
    custom1 Help for the custom1 command
    custom2 Help for the custom2 command
    custom3 Help for the custom3 command
EOF
 
custom1 () {
    echo "custom1"
    # do the stuff for custom1
}
custom2 () {
    echo "custom2"
    # do the stuff for custom2
}
custom3 () {
    echo "custom3"
    # do the stuff for custom3
}

快速查询所有服务的自启动状态, 可以使用以下命令

root@OpenWrt:~# for F in /etc/init.d/* ; do $F enabled && echo $F on || echo $F **disabled**; done
/etc/init.d/boot on
/etc/init.d/bootcount on
/etc/init.d/cron on
/etc/init.d/dnsmasq on
/etc/init.d/done on
/etc/init.d/dropbear on
/etc/init.d/firewall on
/etc/init.d/fstab on
/etc/init.d/gpio_switch on
/etc/init.d/led on
/etc/init.d/log on
/etc/init.d/network on
/etc/init.d/odhcpd on
/etc/init.d/rpcd on
/etc/init.d/samba on
/etc/init.d/shadowsocks-libev on
/etc/init.d/sysctl on
/etc/init.d/sysfixtime on
/etc/init.d/sysntpd on
/etc/init.d/system on
/etc/init.d/transmission on
/etc/init.d/uhttpd on
/etc/init.d/umount **disabled**
/etc/init.d/wifidog **disabled**
原文地址:https://www.cnblogs.com/milton/p/6345621.html