编写测试脚本

#!/bin/bash

# 检查 /tmp 目录下是否存在 out.log 文件,如果不存在则创建
if [ ! -f /tmp/out.log ]; then
    touch /tmp/out.log
fi

# 循环执行,每隔3秒向 /tmp/out.log 追加写入格式字符串
while true; do
    current_time=$(date +"%Y-%m-%d %H:%M:%S")
    echo "[$current_time] hello!" >> /tmp/out.log
    sleep 3
done

编写Systemd 服务脚本

vim sayHello.service
[Unit]
Description=custom sayhello service       # 服务描述
After=syslog.target network-online.target # 启动顺序,这些syslog.target network-online.target 服务之后启动
Wants=network-online.target               # 服务弱依赖

[Service]
User=zklmiao                              # 运行在那个用户组
ExecStart=/home/zklmiao/Doc/sayhello.sh   # 服务拉起测程序执行路径
ExecReload=/bin/kill -s HUP $MAINPID      # 重载信号 程序接收 kill -s Hup 后会重载
Restart=always                            # 崩溃后重启配置
RestartSec=5                              # 重启重试周期
LimitNOFILE=1048576                       # 最大打开文件描述数
LimitNPROC=1048576                        # 最大可创建的进程数量
LimitCORE=1048576                         # 可以生成的核心转储文件大小的限制 单位 bytes 1048576 = 1M
Delegate=yes
KillMode=process                          # 停止服务时,Systemd会按照进程级别来终止相关进程

[Install]
WantedBy=multi-user.target                # 系统处于多用户运行模式时启动服务

ls
# sayHello.service  sayHello.sh

sudo cp sayHello.service /lib/systemd/system
sudo chmod +x /lib/systemd/system/sayHello.service 

启动服务

sudo systemctl daemon-reload           # 重载系统守护进程
sudo systemctl start sayHello.service  # 启动测试服务
sudo systemctl status sayHello.service # 查看测试服务运行情况

● sayHello.service - custom sayhello service
     Loaded: loaded (/lib/systemd/system/sayHello.service; disabled; vendor preset: enabled)
     Active: activating (auto-restart) (Result: exit-code) since Wed 2024-12-11 22:09:17 CST; 1s ago
    Process: 2448 ExecStart=/home/zklmiao/Doc/sayhello.sh (code=exited, status=203/EXEC)
   Main PID: 2448 (code=exited, status=203/EXEC)
sudo systemctl enable sayHello.service #设置自启动
Created symlink /etc/systemd/system/multi-user.target.wants/sayHello.service → /lib/systemd/system/sayHello.service.

停止服务

sudo systemctl stop sayHello.service

卸载服务

sudo systemctl disable sayHello.service
Removed /etc/systemd/system/multi-user.target.wants/sayHello.service.
sudo rm /lib/systemd/system/sayHello.service