math-docs/blog/system-keep-live.md
2023-07-31 11:52:56 +08:00

51 lines
2.0 KiB
Markdown
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
slug: using-systemd-to-keep-a-program-running
title: "使用 Systemd 保持 Linux 系统中的程序长时间保活"
authors: lxy
tags: [ Linux, Systemd ]
---
假设我们有一个可执行程序 `app.sh`(类比 Windows 下的 `app.exe`),我们想用 systemd 进行管理,并保证其在任何情况下都能够保活。下面是具体步骤:
1. 编写 systemd 服务管理配置文件 `/opt/app/app.service`
`[Unit]` 段落中编写一个描述性语句,让人们了解你正在管理什么。在 `[Service]` 段落中定义服务的各个参数:
- `Type=forking` 表示当该服务启动时systemd 假定它会再派生出一个子进程(即父子进程)。这是最常见的 service 类型。
- `ExecStart=` 定义将要启动的可执行程序路径。
- `ExecReload=` 定义重新加载服务时要运行的命令或脚本。
- `Restart=` 当服务失败时自动重启,`always` 是指总是重启,其他选项为 `on-failure``never`
- `WantedBy=multi-user.target` 将这个服务加入启动所需的目标之一。在多用户系统中,`multi-user.target`
是把计算机带到用户登录界面的主要目标。
示例配置如下:
```shell
[Unit]
Description=app daemon
[Service]
Type=forking
ExecStart=/opt/app/app.sh
ExecReload=/opt/app/app.sh
Restart=always
[Install]
WantedBy=multi-user.target
```
2. 将服务管理配置文件做软链接到 `/usr/lib/systemd/system/` 目录下。
通过软链接可以方便地维护服务管理配置文件。示例命令如下:
```shell
ln -s /opt/app/app.service /usr/lib/systemd/system/app.service
```
3.`app.service` 加入系统开机自启动。
```shell
systemctl enable app.service
```
4. 启动程序。
```shell
systemctl start app
```
到此为止,原本的可执行程序 `app.sh` 就已经被 systemd 管理,并保证其在任何情况下都能够保活。