实现Linux系统启动程序自启动方法之一(实证)
在/etc/rc.local文件中编写启动程序的脚本。
1. rc.local文件的配置
1) rc.local的内容
rc.local本质上是一个shell脚本文件,可以把启动时需要执行的命令写在里面,启动时将按顺序执行。就如同在终端执行的命令一样,写入到该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.
解释:
# 添加此文件是为了兼容。
# 强烈建议创建自己的systemd服务或udev规则,以便在引导期间运行脚本,而不是使用此文件。
# 与以前版本不同,由于在引导期间并行执行,此脚本不会在所有其他服务之后运行。
# 请注意,必须运行'chmod+x/etc/rc.local',以确保在引导期间执行此脚本。
虽然Linux强烈建议采用自定义的系统服务实现开机自启动程序,不过我认为在rc.local中配置开机启动程序也是一个不错的方法,因为rc.local的配置更简单明了,所以仍被广泛的使用。
此文件根据自己需求添加内容,例如,我需要开机自动运行桌面目录test中的hello脚本:
#!/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.
cd /home/mylinux/Desktop/test/
sudo ./hello.sh
exit 0
注:文件原始内容的第一行必须有,系统才会识别此文件为脚本文件,如果缺少第一行,该脚本不会运行
2)修改/etc/rc.local的可执行权限。
chmod 777 /etc/rc.local
3)重启服务器。
4)查看是否运行hello程序。
2.如果没有rc.local文件的处理方法
1)在etc/文件夹下面创建rc.local文件
cd /etc/
touch rc.local
2)设置rc-local.service
sudo vim /etc/systemd/system/rc-local.service
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99
[Install]
WantedBy=multi-user.target
3)激活rc-local.service
sudo systemctl enable rc-local.service
4)添加启动服务
#!/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.
# 下面这条是要开机启动的命令
cd /home/mylinux/Desktop/test/
sudo ./hello.sh
exit 0
5)给予脚本执行权限
sudo chmod 777 /etc/rc.local
6)重启服务器检查脚本是否自动运行
3. 应用经验
1)rc.local脚本在操作系统启动时只执行一次。
2)环境变量的问题。
在rc.local脚本中执行程序时是没有环境变量的,如果您执行的程序需要环境变量,可以在脚本中设置环境变量,例如:
#!/bin/sh
appname=`basename $0 | sed s,\.sh$,,`
dirname=`dirname $0`
tmp="${dirname#?}"
if [ "${dirname%$tmp}" != "/" ]; then
dirname=$PWD/$dirname
fi
LD_LIBRARY_PATH=$dirname
export PATH=$LD_LIBRARY_PATH:$PATH
$dirname/$appname "$@"
注:该脚本文件名需要和执行程序文件名一致,所需的库文件与执行程序同在一个文件夹下即可。这也是linux打包程序的一种方法,详细请见《Linux打包发布qt应用程序》
3)rc.local 在最后加 & 符号的问题
在 rc.local 中的命令其实不需要在最后加 & 符号的。所谓后台运行, 对于在终端(Terminal)下运行的命令才有意义。一般来说我们在终端运行一个程序, 该程序就会占用当前终端的标准输入和标准输出, 你就无法在终端运行其他命令了, 这叫前台运行。 如果在终端执行程序的时候在末尾加入一个 & 符号, 程序就会在后台运行, 你仍然可以在当前的终端继续输入其他命令和操作。
而 rc.local 中的命令都是由 init 这个程序来执行的, 他们都会自动在后台运行. 所以这两种写法是不会有差别的.