Linux 系统资源管理 | systemd

发布时间 2023-07-07 18:06:16作者: 菜乌

就系统中通常执行 /etc/init.d/ 目录下的文件来管理服务。

新系统中可统一使用 systemctl 组命令来管理服务。


systemctl 用法

最常用来启动、停止服务

  • systemctl status nginx 查看 nginx 服务状态

  • systemctl start nginx 启动 nginx 服务

  • systemctl stop nginx 停止 nginx 服务

  • systemctl reload nginx 重载 nginx 配置

  • systemctl restart nginx 重启 nginx 服务

  • systemctl enable nginx 设置 nginx 开机自启动


systemctl 是 systemd 的主命令,用来管理系统

  • systemctl reboot 重启系统

  • systemctl poweroff 关机

  • systemctl suspend 暂停系统

  • systemctl hibernate 休眠

  • systemctl hybrid-sleep 交互式休眠

  • systemctl rescue 进入救援状态(单用户状态)

  • systemctl halt CPU 停止工作


其它常用命令

  • systemctl status 显示系统状态

  • systemctl -H root@dev.com status nginx 查看远程主机的 nginx 状态

  • systemctl is-active nginx 查看 nginx 是否运行

  • systemctl is-failed nginx 查看 nginx 是否启动失败

  • systemctl is-enabled nginx 查看 nginx 是否开机自启动

  • systemctl daemon-reload 重载所有修改过的配置文件

  • systemctl kill nginx 杀死 nginx 所有子进程

  • systemctl mask nginx 冻结 nginx 服务

  • systemctl unmask nginx 启用 nginx 服务

  • systemctl show nginx 显示 nginx 的所有底层参数

  • systemctl show -p CPUShares nginx 显示 nginx 的指定属性的值

  • systemctl set-property nginx CPUShares=500 设置 nginx 的指定属性


unit 管理

systemd 可以管理所有系统资源,统称为 unit

查看系统所有资源

  • systemctl list-units --all 列出所有Unit

  • systemctl list-units 列出正在运行的 Unit

  • systemctl list-units --type=service 列出正在运行的 service

  • systemctl list-units --all --state=inactive 列出所有没有运行的 Unit

  • systemctl list-units --failed 列出所有加载失败的 Unit


资源类型

通过上面查看资源的命令可以看到有不同的资源

  • .automount 自动挂载点

  • .device 硬件设备

  • .mount 文件系统的挂载点

  • .path 文件或路径

  • .scope 不是由 Systemd 启动的外部进程

  • .service 系统服务

  • .slice 进程组

  • .snapshot Systemd 快照,可以切回某个快照

  • .socket 进程间通信的 socket

  • .swap swap 文件

  • .target 多个 Unit 构成的一个组

  • .timer 定时器


资源依赖

unit 之间存在依赖关系,比如启动 perl-fastcgi 之前需启动 nginx

  • systemctl list-dependencies nginx 列出 nginx 服务的所有依赖

  • systemctl list-dependencies --all nginx 展开显示 nginx 服务的所有依赖


service 状态

loaded 系统服务已经初始化完成,加载过配置

active(running)执行中

active(exited) 仅执行一次就正常的服务

inactive 服务关闭

enbaled 服务开机启动

disabled 服务开机不自启

static 服务开机启动项不可被管理

failed 系统配置错误

资源配置

每个 unit 都有一个配置文件,说明启动停止等方式

  • 配置文件默认在 /etc/systemd/system 各目录下,并软连接到 /usr/lib/systemd/system 目录

  • enable 设置自启动就会创建两个目录的软连接

  • 相反,disable 会删除软连接,关闭开机自启动

  • systemd 也会去 /etc/init.d/ 查找、运行相关资源

  • 查看所有配置文件

    # 列出所有配置文件
    systemctl list-unit-files
    
    # 列出类型为 service 的配置文件
    systemctl list-unit-files --type=service
    
  • 配置文件状态

    static:该配置文件没有[Install]部分(无法执行),只能作为其他配置文件的依赖
    enabled:已建立启动链接
    disabled:没建立启动链接
    masked:该配置文件被禁止建立启动链接
    


systemd 还有其它内容,学习后再来补充