阅读量:344
在Ubuntu系统中,为了使一个程序在开机时自动启动,通常可以通过修改rc.local文件来实现。然而,Ubuntu系统中有两个rc.local文件,它们是/etc/rc.local和/etc/init.d/rc.local。这两个文件之间的关系可以通过查看它们的内容来理解。
bash
/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 ] \u0026\u0026 log_begin_msg 'Running local boot scripts (/etc/rc.local)'
/etc/rc.local \u003e/dev/null 2\u003e\u00261 || exit $?
[ '$VERBOSE' != no ] \u0026\u0026 log_end_msg $?
fi
}
case '$1' in
start) do_start ;;
restart|reload|force-reload) echo 'Error: argument '$1' not supported' \u003e\u00262 exit 3 ;;
stop) ;;
) echo 'Usage: $0 start|stop' \u003e\u00262 exit 3 ;;
esac
从注释中可以看出,这个脚本在启动级别的2、3、4、5下运行,仅支持start参数,并在存在/etc/rc.local文件时执行它。如果要将程序添加到/etc/init.d/rc.local文件中以实现开机启动,需要注意不要将所有内容直接添加到文件的最后,因为在case语句块中,脚本会提前退出。
bash
/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系统,如果您的系统版本不同,请查阅相应版本的官方文档以获取最准确的信息。