系统学习 Linux 学习路径:从文件与进程到排障与安全

systemctl

控制 systemd 系统与服务单元的命令行入口。

补充说明

systemd 把服务、套接字、定时器、挂载点等统称为 unit。systemctl 同时管理运行时状态和开机启用状态:start/stop 改变当前运行状态,enable/disable 只增删安装链接,二者互不等价。mask 把单元链接到 /dev/null,比 disable 更强,会阻止手动启动和依赖拉起。

修改磁盘上的 unit 文件后,运行中的 manager 仍持有旧配置,需要 systemctl daemon-reload;systemctl reload 单元 则是让服务自己重读配置,含义完全不同。排查时我优先用 systemctl cat 看实际加载的文件和 drop-in,用 systemctl show -p ... 取机器可读属性,再用 journalctl -u 看失败原因;unit 语法错误可用 systemd-analyze verify 提前发现。

常用示例

# 查看状态和最近日志;-l 不截断,--no-pager 适合脚本或日志粘贴
systemctl status nginx --no-pager -l
# 运行时控制;reload 要求服务本身支持重载
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx
# 启用并立即启动;仅 enable 不会启动服务
systemctl enable --now nginx
systemctl disable --now nginx
# 彻底屏蔽与解除;mask 会阻止手动启动和依赖拉起
systemctl mask --now nginx
systemctl unmask nginx
# 查看失败单元、运行中的服务和已启用单元
systemctl --failed
systemctl list-units --type=service --state=running
systemctl list-unit-files --state=enabled
# 查看单元文件来源与当前属性
systemctl cat nginx
systemctl show -p ActiveState -p SubState -p MainPID nginx

# 创建 drop-in 覆盖配置;修改文件后必须手动重载
systemctl edit nginx
systemctl daemon-reload

# 定时器、用户管理器、脚本判断、语法校验
systemctl list-timers --all
systemctl --user status my.service
systemctl is-active --quiet nginx && echo active
systemd-analyze verify /etc/systemd/system/foo.service

易错点与排错

相关命令

参考链接

读完自测

合上页面,先回答,再展开对照。

  1. 修改 /etc/systemd/system/foo.service 后,为什么 restart 仍可能使用旧配置?完整操作顺序是什么?
  2. enable、start、mask 三者分别改变什么?哪个会阻止手动启动?
  3. 脚本中如何可靠判断服务是否活跃?为什么不建议解析 systemctl status 的输出?
答案
  1. systemd manager 仍持有已加载的旧单元,需要先 systemctl daemon-reload,再 systemctl restart foo.service。若通过 systemctl edit 修改 drop-in,成功编辑通常会自动触发 reload。
  2. enable 增删开机安装链接,start 改变当前运行状态,mask 链接到 /dev/null 阻止启动。mask 会阻止手动启动和依赖拉起,且默认不停止正在运行的服务。
  3. 用 systemctl is-active --quiet foo.service 判断退出码。status 的输出格式面向人阅读,可能随版本和本地化变化,不适合作为稳定的机器接口。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令