深入探索systemd单元管理
立即解锁
发布时间: 2025-09-13 00:43:20 阅读量: 9 订阅数: 20 AIGC 

# 深入探索 systemd 单元管理
## 1. 引言
在 Linux 系统管理中,systemd 是一个强大的工具套件,它能帮助我们管理系统的各个方面,包括服务、设备、挂载点等。本文将详细介绍如何使用 systemd 单元以及相关的 `systemctl` 命令,同时通过实际实验来演示具体操作。
## 2. 准备工作
### 2.1 安装 sysstat 包
为了后续实验,我们需要安装 `sysstat` 包,它包含了一些用于系统性能统计的工具,如 SAR(System Activity Reporter)。使用以下命令进行安装:
```bash
[root@studentvm1 ~]# dnf -y install sysstat
```
### 2.2 systemd 套件概述
systemd 不仅仅是一个单一的程序,而是一套大型的程序集合,它们协同工作,管理 Linux 系统运行的各个方面。虽然系统管理不需要了解所有 systemd 组件的细节,但掌握其核心程序和组件有助于管理各种 Linux 服务、处理日志文件和日志。
## 3. 认识 unit 文件
### 3.1 unit 文件的基本概念
systemd 的结构除了可执行文件外,主要包含在众多配置文件中,这些文件被称为“unit”文件。Unit 文件是 ASCII 纯文本文件,系统管理员可以访问、修改或创建它们。Unit 文件有多种类型,每种类型都有自己的手册页。
### 3.2 unit 文件类型示例
| 文件扩展名 | 描述 |
| --- | --- |
| .service | 服务单元,用于管理系统服务 |
| .mount | 挂载单元,用于管理文件系统挂载 |
| .target | 目标单元,用于组织和控制其他单元 |
| .timer | 定时器单元,用于定时执行任务 |
## 4. 使用 systemctl 命令
### 4.1 查看已加载和活跃的 systemd 单元
在终端中以 root 用户身份执行以下命令,查看所有已加载和活跃的 systemd 单元:
```bash
[root@studentvm1 ~]# systemctl
```
输出结果包含多个部分,如设备、文件系统挂载点、服务和目标等。输出的最后会显示状态、加载、活跃和子状态的含义。按 `q` 键退出分页器。
### 4.2 查看所有安装的单元文件
使用以下命令查看所有安装的单元文件,无论它们是否已加载:
```bash
[root@studentvm1 ~]# systemctl list-unit-files
```
### 4.3 按类型查看单元文件
- **查看定时器单元**
```bash
[root@studentvm1 ~]# systemctl list-unit-files -t timer
```
- **查看挂载点单元文件**
```bash
[root@studentvm1 ~]# systemctl list-unit-files -t mount
```
- **查看服务单元文件**
```bash
[root@studentvm1 ~]# systemctl --all -t service
```
### 4.4 单元文件状态解释
在查看挂载点单元文件时,`STATE` 列的状态需要解释:
- **generated**:表示挂载单元在启动时根据 `/etc/fstab` 中的信息动态生成。
- **static**:表示挂载单元用于 `/proc` 和 `/sys` 等文件系统,相关文件位于 `/usr/lib/systemd/system` 目录。
## 5. 探索单元文件
### 5.1 查看默认目标文件
默认目标文件 `default.target` 决定系统启动时的运行级别。查看其内容:
```bash
[root@studentvm1 system]# cat default.target
```
内容示例:
```plaintext
# SPDX-License-Identifier: LGPL-2.1+
#
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
[Unit]
Description=Graphical Interface
Documentation=man:systemd.special(7)
Requires=multi-user.target
Wants=display-manager.service
Conflicts=rescue.service rescue.target
After=multi-user.target rescue.service rescue.target display-manager.service
AllowIsolate=yes
```
### 5.2 分析单元文件依赖关系
从 `default.target` 文件可以看出,它依赖于 `multi-user.target`,并且“想要” `display-manager.service` 单元。“想要”并不意味着必须满足才能启动单
0
0
复制全文
相关推荐









