全面解析 Linux 中的运行级别,从 SysV init 到 systemd
运行级别是 Linux 系统处于某种状态或模式的标志。它决定了哪些服务应该启动或停止。每个运行级别对应一个特定的系统状态,如单用户模式、图形界面、关机等。
在传统的 SysV init 系统中,运行级别由数字表示(0 到 6)。而在 modern Linux 发行版(如 CentOS 7+/Debian 8+/Ubuntu 16.04+)中,systemd 接管了 init 系统,运行级别由“目标(Target)”来取代,但本质上仍可对应传统级别。
传统 SysV Init 运行级别
SysV init 使用 /etc/inittab 配置文件指定默认运行级别,通过启动对应目录下的脚本来启动或停止服务。
各运行级别的含义如下:
运行级别 | 状态描述 |
0 | 停机(关机) |
1 | 单用户模式(维护/恢复) |
2 | 多用户模式(无网络) |
3 | 多用户模式(带网络,命令行) |
4 | 自定义(一般未使用) |
5 | 多用户模式(带图形界面) |
6 | 重启系统 |
注意:运行级别 0 和 6 不应作为默认运行级别,否则系统会陷入关机或重启循环。
查看当前运行级别
runlevel
输出示例:
N 3
含义:当前运行级别为 3,“N” 表示无法检测上一个运行级别(如系统刚启动)。
切换运行级别
init 5 # 切换到图形界面
init 3 # 切换到命令行模式
或使用:
telinit 1 # 切换到单用户模式
设置默认运行级别
编辑 /etc/inittab:
id:3:initdefault:
保存后,系统下次启动默认进入运行级别 3。
启动脚本路径与运行级别的关系
各运行级别对应的服务脚本目录如下:
/etc/rc.d/rc0.d/
/etc/rc.d/rc1.d/
/etc/rc.d/rc2.d/
/etc/rc.d/rc3.d/
/etc/rc.d/rc5.d/
/etc/rc.d/rc6.d/
这些目录中包含 S(start)和 K(kill)开头的链接,指向 /etc/init.d/ 目录下的实际服务脚本。
例如:
/etc/rc.d/rc3.d/S80httpd -> /etc/init.d/httpd
表示在运行级别 3 中启动 Apache 服务。
systemd 下的“运行级别”:Target 机制
随着 systemd 的引入,传统的运行级别机制被更灵活的 Target 所取代。虽然 runlevel 命令仍然可用,但它已成为对 systemd 的兼容层。
常见 Target 对应关系
SysV 级别 | systemd Target |
0 | poweroff.target |
1 | rescue.target |
3 | multi-user.target |
5 | graphical.target |
6 | reboot.target |
查看当前运行级别(Target)
systemctl get-default
或使用:
systemctl list-units --type=target
设置默认启动 Target
sudo systemctl set-default multi-user.target
临时切换 Target(不会影响下次启动)
sudo systemctl isolate graphical.target
启动/停止服务对应 Target
查看某个 Target 包含的服务:
systemctl list-dependencies multi-user.target
创建自定义运行级别(Target)
- 创建一个自定义 target 文件:
sudo cp /usr/lib/systemd/system/multi-user.target /etc/systemd/system/my-custom.target
- 修改内容或添加依赖服务:
[Unit]
Description=My Custom Runlevel
Requires=network.target sshd.service
After=network.target
- 重新加载配置:
sudo systemctl daemon-reexec
sudo systemctl set-default my-custom.target
System V vs systemd
特性对比 | SysV init | systemd |
启动方式 | 顺序执行启动脚本 | 并行启动,提高速度 |
运行级别 | 数字(0-6) | target(如 multi-user.target) |
服务管理 | service 命令 | systemctl 命令 |
脚本路径 | /etc/init.d/ | /usr/lib/systemd/system/ 等 |
兼容性 | 旧系统使用 | 新系统主流,兼容传统方式 |
运行级别不仅是历史遗产,它们仍然以“目标”的形式深深嵌入 modern Linux 系统之中。无论你管理的是经典的 CentOS 6,还是现代的 Ubuntu 20.04,理解运行级别及其现代替代机制 Target,都是迈向资深 Linux 管理员的重要一步。