跳到主要内容

进程与服务管理

现代 Linux 多数发行版使用 systemd 作为初始化系统和服务管理器,理解其概念是日常运维的关键。

systemd 单元类型

systemd 通过单元(Unit)管理各种资源,常见类型:

  • service:系统服务,如 nginx、sshd。
  • timer:定时任务,替代 cron。
  • socket:套接字,按需激活相关服务。
  • target:一组单元的集合,代表运行级别。
  • mount/automount:挂载点管理。

单元文件位于 /usr/lib/systemd/system/(发行版自带)与 /etc/systemd/system/(管理员自定义),后者优先级更高。

systemctl 常用操作

sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # 平滑重载配置
sudo systemctl status nginx
sudo systemctl enable nginx # 设置开机自启
sudo systemctl disable nginx
sudo systemctl list-units --type=service --state=running

enable 创建符号链接指向 /etc/systemd/system/ 对应 target 的 wants 目录,disable 则是反向操作。

journalctl 查看日志

systemd 将日志统一收集在 journald 中,通过 journalctl 查询。

journalctl -u nginx # 指定服务
journalctl -u nginx -f # 实时跟踪
journalctl -u nginx --since "1 hour ago"
journalctl -p err # 仅显示错误及以上
journalctl --since today --until "1 hour ago"

日志默认二进制存储,可通过 /etc/systemd/journald.conf 调整持久化与大小限制。

守护进程与后台任务

传统上,守护进程(daemon)是脱离终端在后台运行的服务。手动将任务放到后台可用:

command & # 后台运行
jobs # 查看当前 shell 的后台任务
fg %1 # 将任务 1 调到前台
bg %1 # 继续在后台执行被挂起的任务
nohup cmd & # 忽略挂起信号,适合 SSH 断开后继续运行

nohup 配合 & 可让进程在退出登录后继续运行,输出默认重定向到 nohup.out

cgroup 简介

cgroup(control groups)是 Linux 内核特性,用于限制、记录和隔离进程组的资源使用(CPU、内存、IO 等)。systemd 自动为每个服务创建 cgroup,可通过 systemctl statussystemd-cgtop 查看资源占用。理解 cgroup 有助于排查资源争抢与配置容器。