<!--
 * @Author: your name
 * @Date: 2021-07-09 11:39:19
 * @LastEditTime: 2021-09-07 09:27:05
 * @LastEditors: kindring
 * @Description: In User Settings Edit
 * @FilePath: \md-\linux\开机自启相关.md
-->
# 使用 `systemctl` 配置服务.并且使其自启动
## 新增服务
> [!note]
> ubuntu 21.04
### 定义服务
在 `/lib/systemd/system/` 目录下创建文件 `serverName.service`

> [!warning]
> serverName 替换为自己需要的服务名称,可以直接执行下面的代码

修改文件,使用`vim`来进行编辑, 在shell
```shell
vim /lib/systemd/system/serverName.service
```
通过`vim`打开`serverName.service`后继续输入下方代码,其中的 `server` 替换成执行任务
```shell
[Unit]
Description=fraps service
After=network.target network-online.target syslog.target
Wants=network.target network-online.target
[Service]
Type=simple
#要启动的命令(此处根据实际情况填写)
ExecStart= #server 执行的任务,此注释替换新的
[Install]
WantedBy=multi-user.target
```
### 启用服务
```shell
sudo systemctl enable serverName
```
### 启动服务进程
```shell
sudo systemctl start serverName
```
### 常用命令
> [!tip]
> 常用命令基本上分为 start restart stop 
 
 <!-- tabs:start -->
#### **启动服务进程**
```shell
sudo systemctl start serverName
```
#### **重启服务**
```shell
sudo systemctl restart serverName
```
#### **关闭服务**
```shell
sudo systemctl stop serverName
```
#### **启用服务**
```shell
sudo systemctl enable serverName
```
#### **停用服务**
```shell
sudo systemctl disable serverName
```
<!-- tabs:end -->
### 问题解决
> [!warning]
> 如果重新修改了服务文件需要执行`systemctl daemon-reload`重新加载
> Warning: The unit file, source configuration file or drop-ins of githook.service changed on disk. Run > 'systemctl daemon-reload' to reload units.
```shell
  systemctl daemon-reload
```
## 日志查看
> [!tip]
> 查看服务日志使用 `journalctl -u 服务名`
> `journalctl`用来查看`systemctl`搜集到的日志,可以用来调试排查问题. 据说是`systemctl`携带的
### 使用示例
查看服务名为`githook`的服务日志
```shell
journalctl -u githook.service
```
### 更多使用技巧
1. **查看最近的日志**

携带参数`n`加数字可以看到最近`n`条日志

代码示例
```shell
journalctl -n 100 -u githook.service
```