查看当前的运行级别

2025-07-08 19:56:00
丁国栋
原创 30
摘要:查看当前的运行级别。

ubuntu 如何查看当前的运行级别?


Ubuntu 14.04 LTS (Trusty Tahr) 是最后一个默认使用 Upstart 的版,Ubuntu 从 15.04(Vivid Vervet) 开始正式使用 systemd 替代传统的 Upstart 作为默认的初始化系统(init system)。在 Ubuntu 20.04.4 LTS(使用 systemd)中,传统的运行级别(runlevel)概念已被 systemd 的 target 取代。


注:Upstart 是由 Canonical(Ubuntu 的母公司) 开发的一种事件驱动的初始化系统(init system),用于替代传统的 SysVinit。它被设计为更现代化、更高效的系统启动和管理工具。Upstart 兼容 SysVinit 脚本,支持传统的 /etc/init.d/ 脚本,使得过渡更加平滑。曾在 Ubuntu 6.10(Edgy Eft)至 14.10(Utopic Unicorn)期间作为默认的 init 系统,直到 Ubuntu 15.04(Vivid Vervet) 被 systemd 取代。


方法 1:通过 systemctl 查看当前 target

systemctl get-default

这会显示默认的 target(如 multi-user.targetgraphical.target)。

要查看当前正在运行的 target:

systemctl list-units --type=target --state=active

注:Systemd 中的 target 不仅有运行级别, 也用于标记系统某一类服务或资源已就绪,并且可以作为其他服务的启动条件。例如达到 network.target 仅表示网络栈已初始化但不保证联网成功,而达到 network-online.target 表示网络已真正连通。

如果一个服务需要在网络连通后启动,可以在其 unit 文件中添加:

[Unit]
After=network-online.target
Wants=network-online.target

方法 2:将 target 映射到传统运行级别

Ubuntu 的 target 与传统运行级别的对应关系:

  • poweroff.target → 运行级别 0(关机)
  • rescue.target → 运行级别 1(单用户模式)
  • multi-user.target → 运行级别 2/3/4(多用户命令行)
  • graphical.target → 运行级别 5(图形界面)
  • reboot.target → 运行级别 6(重启)

方法 3:使用 who -r(仅显示上次切换记录)

who -r

这会显示上次的 target 切换记录(非实时状态)。


方法 4:检查当前是否在图形界面

如果以下命令返回 active,说明图形界面正在运行:

systemctl is-active graphical.target

注意事项

  • 在使用 systemd 后的 Ubuntu 发行版已不再使用 /etc/inittab 文件设定运行级别,但依然可以使用 runlevel 命令查看上一次和当前的运行级别。
  • 如果需要切换 target 可以使用 sudo systemctl isolate [target名](如切换到命令行:sudo systemctl isolate multi-user.target)。
发表评论
博客分类