Ubuntu rc.local 文件机制与配置指南
前言
在Ubuntu环境下,若需将自定义程序设置为开机自启动,通常涉及对rc.local文件的修改。然而,该系统中存在两个名称相似但功能不同的rc.local文件,分别位于/etc/rc.local和/etc/init.d/rc.local。通过对比这两个文件的内容,可以清晰理解它们之间的依赖关系。
/etc/init.d/rc.local
#! /bin/sh
### BEGIN INIT INFO
# Provides: rc.local
# Required-Start: $all
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop:
# Short-Description: Run /etc/rc.local if it exist
### END INIT INFO
PATH=/sbin:/usr/sbin:/bin:/usr/bin
. /lib/init/vars.sh
. /lib/lsb/init-functions
do_start() {
if [ -x /etc/rc.local ]; then
[ "$VERBOSE" != no ] && log_begin_msg "Running local boot scripts (/etc/rc.local)"
/etc/rc.local
ES=$?
[ "$VERBOSE" != no ] && log_end_msg $ES
return $ES
fi
}
case "$1" in
start)
do_start
;;
restart|reload|force-reload)
echo "Error: argument '$1' not supported" >&2
exit 3
;;
stop)
;;
*)
echo "Usage: $0 start|stop" >&2
exit 3
;;
esac
从脚本注释可知,该初始化脚本主要在运行级别2、3、4和5时执行。它仅支持start参数,当接收到启动指令时,会检查是否存在/etc/rc.local文件,若存在则执行之。需要注意的是,切勿将自定义启动命令直接追加到/etc/init.d/rc.local文件的末尾,因为该脚本包含case语句块,处理完相应逻辑后会直接退出,导致后续代码无法执行。
/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.
exit 0
该文件内容较为简单,主要作为模板供用户添加开机自启动任务。用户只需将需要执行的程序命令放置在exit 0这一行之前即可生效。
因此,要实现开机启动项的添加,只需编辑/etc/rc.local文件并在其中添加相应的启动命令即可。
Ubuntu系统的启动级别定义如下:
0:关机状态
1:单用户模式
2至5:多用户图形界面模式
6:重启状态
针对上述每个启动级别,/etc目录下均设有对应的目录(如/etc/rc5.d/),其中包含一系列脚本。这些脚本大多是指向/etc/init.d/目录下对应服务的软链接,文件名中的数字代表启动优先级。系统在启动过程中会依次执行这些脚本。
备注:本示例基于Ubuntu 15.04系统环境。
总结
以上内容涵盖了Ubuntu中rc.local相关文件的核心机制与配置方法,希望能为读者在学习或工作中提供帮助。如有任何疑问,欢迎留言交流,感谢对本站的支持。