Linux 自启动流程:
[1] - 加载BIOS的硬件信息与进行自我测试, 并依据设置取得第一个可启动的设备;
[2] - 读取并执行第一个启动设备内MBR的boot loader(即grub、spfdisk等程序);
[3] - 一句boot loader 的设置加载Kernel,Kernel会开始检测硬件与加载驱动程序;
[4] - 在硬件驱动成功后,Kernel会主动调用init进程,而 init 会取得 run-level 信息;
[5] - init 执行/etc/rc.d/rc.sysinit 文件来准备软件执行的操作环境(如网络时区等);
[6] - init 执行 run-level 的各个服务器的启动(script方式);
[7] - init 执行/etc/rc.d/rc.local 文件;
[8] - init 执行终端机模拟程序 mingetty 来启动login 进程,最后就等待用户登陆。
1. rc.local 自启动
如,在 rc.local 文件添加日志输出功能,根据是否有日志文件生成,判断 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.
#log
echo "test rc.local" > rc.local.log
sleep 30 #等待 30秒
set -x #display commands before execution
exit 0
生效自启动:
source /etc/rc.local
2. rc.local 状态与重启
#状态
systemctl status rc.local
#重启
systemctl restart rc.local
3. rc.local 注意事项
[1] - rc.local 等相关执行文件添加执行权限
chmod 755 rc.local
#或
chmod +x xxx
[2] - 使用绝对路径
[3] - bash 代替 sh
#!/bin/sh
#对应bin中的dash,版本老,有些新命令不支持,从而报错
#!/bin/bash 推荐
注,查看软链接实际指向位置:
ls -al
#如:
#sh -> dash
4. Ubuntu20.04 启用 rc.local
比较新的Linux发行版已经没有rc.local文件,而是将其服务化了.
[1] - 编辑 /lib/systemd/system/rc-local.service
# sudo vim /lib/systemd/system/rc-local.service
# SPDX-License-Identifier: LGPL-2.1+
#
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no
末尾添加如下内容:
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
[2] - 激活 rc-local.service
sudo ln -s /lib/systemd/system/rc-local.service /etc/systemd/system/rc-local.service
#或,若未成功
sudo systemctl enable rc-local
sudo systemctl start rc-local