# systemctl
```bash
systemctl start service #开启服务
systemctl stop service #关闭服务
systemctl status service #显示状态
systemctl restart service #重启服务
systemctl enable service #开机启动服务
systemctl disable service #禁止开机启动
systemctl list-units #查看系统中所有正在运行的服务
systemctl list-unit-files #查看系统中所有服务是否开机启动
systemctl mask service #冻结服务
systemctl unmask service #解冻服务
systemctl list-dependencies service #查看系统中服务的依赖关系
systemctl set-default multi-user.target #开机时不启动图形界面
systemctl set-default graphical.target #开机时启动图形界面
systemctl --version #查看systemd版本
```
| 状态 | 含义 |
| --------------- | ------------------------------------------------------ |
| active(running) | 表示程序正在执行 |
| atcive(exited) | 执行一次就正常退出的服务,不在系统中执行任何程序 |
| active(waiting) | 正在执行中,处于阻塞状态,需要等待其他程序执行完才能执行 |
| inactive (dead) | 未启动状态 |
| 启动状态 | 含义 |
| -------- | -------------------- |
| inactive | 服务关闭 |
| disable | 服务开机不启动 |
| enabled | 服务开机启动 |
| static | 服务开机启动项被管理 |
| failed | 服务配置错误 |
| masked | 服务被锁定 |
systemctl命令管理systemd的资源Unit
systemd的Unit放在用户目录 **/usr/lib/systemd/system (Centos和Ubuntu)** 或者 **/etc/systemd/system (Ubuntu)**。
主要有四种类型文件.mount、.service、.target、.wants
**.mount 文件**
.mount文件定义了一个挂载点,[Mount]节点里配置了What,Where,Type三个数据项
等同于以下命令:
mount -t hugetlbfs /dev/hugepages hugetlbfs
**.service 文件**
.service文件定义了一个服务,分为[Unit],[Service],[Install]三个小节。
```bash
[Unit]
Description=OpenBSD Secure Shell server
After=network.target auditd.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run
[Service]
EnvironmentFile=/etc/default/ssh
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
Restart=on-failure
[Install]
Alias=sshd.service
WangtedBy=multi-user.target
===============================================================
[Unit]
Description:描述,
After:在network.target,auditd.service启动后才启动
ConditionPathExists: 执行条件
[Service]
EnvironmentFile:变量所在文件
ExecStart: 执行启动脚本
Restart: fail时重启
[Install]
Alias:服务别名
WangtedBy: 多用户模式下需要的
```
**.target 文件**
.target定义了一些基础的组件,供.service文件调用
**.wants 文件**
.wants文件定义了要执行的文件集合,每次执行,.wants文件夹里面的文件都会执行
# service
```bash
# service被systemctl代替
service -h
service --status-all #显示所服务的状态
```
| daemon命令 | systemctl命令 |
| ---------------------- | ----------------------------- |
| service [服务] start | systemctl start [unit type] |
| service [服务] stop | systemctl stop [unit type] |
| service [服务] restart | systemctl restart [unit type] |
# init
```bash
# init被systemctl代替
```
| init命令 | systemctl命令 | 说明 |
| :------- | :----------------- | :------- |
| init 0 | systemctl poweroff | 系统关机 |
| init 6 | systemctl reboot | 重新启动 |
| systemctl命令 | 说明 |
| :------------------ | :------------------- |
| systemctl suspend | 进入睡眠模式 |
| systemctl hibernate | 进入休眠模式 |
| systemctl rescue | 强制进入救援模式 |
| systemctl emergency | 强制进入紧急救援模式 |
| init级别 | systemctl target |
| :------- | :---------------- |
| 0 | shutdown.target |
| 1 | emergency.target |
| 2 | rescure.target |
| 3 | multi-user.target |
| 4 | 无 |
| 5 | graphical.target |
| 6 | 无 |