systemctl进程管理

发布于:2024-04-03 ⋅ 阅读:(153) ⋅ 点赞:(0)

1,创建并编辑一个测试脚本

root@orangepizero3:/work/06-runit/mytest# vi /work/06-runit/mytest/test.sh

脚本循环每秒打印一个数据到指定文件/work/06-runit/mytest/log.txt,30秒后退出。

#!/bin/bash

echo "[zhou] Started service..."

for i in {1..30}
do
  echo "[zhou] Doing : $i" > /work/06-runit/mytest/log.txt 2>&1
  sleep 1
done
echo "[zhou] Oh no I crashed..." >&2
exit 1
~

2,创建并编辑一个服务

vi /work/06-runit/mytest/mytest.service

定义启动服务时需要运行的脚本: /work/06-runit/mytest/test.sh
服务重启的延迟时间:RestartSec
服务在非正常退出后会自动重启: Restart=on-failure
Restart= 是一个在 Systemd 服务单元文件中使用的指令,用于控制服务的重启行为。它有以下几种选项:

  1. no(默认):表示服务不会自动重启。
  2. on-success:表示服务在成功退出后会自动重启。
  3. on-failure:表示服务在非正常退出后会自动重启。
  4. on-abnormal:表示服务在异常退出后会自动重启。
  5. on-abort:表示服务在被强制终止后会自动重启。
  6. always:表示服务总是会自动重启,无论退出状态如何。
[Unit]
Description=my_a02

[Service]
#ExecStart=/work/02-template/template/app_x86/dist/a02.sh
ExecStart=/work/06-runit/mytest/test.sh
Restart=on-failure
RestartSec=3s
User=root

[Install]
WantedBy=multi-user.target

3,部署服务

创建软链接:

ln -s /work/06-runit/mytest/mytest.service /etc/systemd/system/mytest.service

权限授予:

chmod +x /etc/systemd/system/mytest.service

启用服务(在系统启动时自动启动):

systemctl enable mytest.service

重新加载 Systemd 的配置文件,使修改后的配置文件生效:

systemctl daemon-reload

启动服务:

systemctl start mytest.service

查看服务状态

root@orangepizero3:/work/06-runit/mytest# systemctl status mytest.service
● mytest.service - my_a02
     Loaded: loaded (/etc/systemd/system/mytest.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2024-04-03 09:48:13 UTC; 13s ago
   Main PID: 54117 (test.sh)
      Tasks: 2 (limit: 2204)
     Memory: 512.0K
        CPU: 108ms
     CGroup: /system.slice/mytest.service
             ├─54117 /bin/bash /work/06-runit/mytest/test.sh
             └─54130 sleep 1

Apr 03 09:48:13 orangepizero3 systemd[1]: Started my_a02.
Apr 03 09:48:13 orangepizero3 test.sh[54117]: [zhou] Started service...
root@orangepizero3:/work/06-runit/mytest#

4,打印日志查看

从日志看出,脚本退出后被重新拉起了:

root@orangepizero3:/work/06-runit/mytest# tail -f ./log.txt
[zhou] Doing : 30
tail: ./log.txt: file truncated
[zhou] Doing : 1
tail: ./log.txt: file truncated
[zhou] Doing : 2
tail: ./log.txt: file truncated
[zhou] Doing : 3
tail: ./log.txt: file truncated
[zhou] Doing : 4
tail: ./log.txt: file truncated
[zhou] Doing : 5
tail: ./log.txt: file truncated
[zhou] Doing : 6
tail: ./log.txt: file truncated
[zhou] Doing : 7