51 lines
2.0 KiB
Markdown
Executable File
51 lines
2.0 KiB
Markdown
Executable File
---
|
||
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 管理,并保证其在任何情况下都能够保活。 |