起因

写一个监测网站更新的脚本,检测到更新后自动发送邮件到邮箱通知我

过程

shell脚本如下

#!/bin/bash
./main.py
dos2unix detect_log
mail -s "Update Detected!" xxxxx@qq.com < detect_log

把它添加到守护进程中,初始文件test-web.service如下

[Unit]
Description=Test Web Detect Shell Service
After=network.target

[Service]
ExecStart=/root/web_detect/test.sh
WorkingDirectory=/root/web_detect/
Restart=always

[Install]
WantedBy=default.target

但是运行发现,总是出现错误

. . . message not sent.

但是命令行窗口运行shell脚本正常,而守护进程就不正常

解决方法

在谷歌上搜到在systemd中使用mail发送邮件失败的坑

提到了systemctl运作原理:

mail在发送邮件的时候会fork出一个sendmail的子进程来实现功能,而sendmail会变成一个守护进程。systemd在执行玩这个任务的时候会杀死其进程组下的所有进程,所以sendmail也被直接杀死,导致了邮件无法发送。解决的办法是在service单元下修改killmode为process。process表示只杀主进程,这样在退出后sendmail也不会被systemd强制杀死。

[Unit]
Description=Test Web Detect Shell Service
After=network.target

[Service]
ExecStart=/root/web_detect/test.sh
WorkingDirectory=/root/web_detect/
Restart=always
KillMode=process	# 添加代码

[Install]
WantedBy=default.target

山和山不相遇,人与人要相逢