当前位置:   article > 正文

systemd实现python的守护进程_systemd-python

systemd-python

守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。(摘自百度百科

之前有转过一遍python实现守护进程方法的博客,这次我们看看用systemd是如何实现的。

有关systemd的介绍和使用推荐阮一峰老师的以下两篇博客,写的非常详细和全面

下面我们看看用systemd如何实现守护进程(我的环境Centos 7

#!/usr/bin/env python
# -*- coding=utf-8 -*-


"""
每隔5秒输出本地时间到指定的文件
path: /home/test.py
"""

import time


filepath = '/home/time' # 文件路径
fm = '%Y-%m-%d %X'

def get_time():
	while 1:
	    nowtime = time.strftime(fm, time.localtime())
	    with open(filepath, 'a') as fp:
	        fp.write(nowtime)
	        fp.write('\n')
	    time.sleep(5)
    
if __name__ == '__main__':
    get_time()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

接着我们在/home目录下创建一个systemd的文件test.service

[Unit]
Description=test deamon
After=rc-local.service

[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/home
ExecStart=/usr/bin/python test.py
Restart=always

[Install]
WantedBy=multi-user.target
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

把此文件复制到systemd目录下: cp /home/test.service /etc/systemd/system/

启动: systemctl start test.service

ps -ef | grep python 查看python进程会发现多了/usr/bin/python test.py的进程

当我们人为kill掉此进程的时候,systemd会自动帮我们重启此进程

启动后查看time文件就会看到每隔5秒输出时间了: tail -f /home/time

停止: systemctl stop test.service

如果想开机启动此服务

$ systemctl enable test.service
# 以上命令相当于执行以下命令,把test.service添加到开机启动中
$ sudo ln -s  '/etc/systemd/system/test.service'  '/etc/systemd/system/multi-user.target.wants/test.service' 
  • 1
  • 2
  • 3

systemd 实现守护进程是不是so easy 啊!比起python代码方式实现真的容易方便多了

注:现在大部分Linux衍生版本都支持systemd(如centos,deepin),部分不支持(如:Ubuntu14.04之前的版本)

查看系统是否支持systemd:systemctl --version 如果提示未找到命令则说明系统不支持systemd

查看系统详细信息:hostnamectl


注:由systemd起的任何服务,当我们停掉该systemd时,服务也会随之停掉

比如说,我们自己定义了一个systemd service,用来执行某python脚本,而该脚本启动mysql、nginx服务,当我们停掉该systemd service(systemctl stop xxx.service)时,mysql和nginx服务也会停(kill)掉。因为这两个服务是有systemd起的,当systemd服务停/kill掉时,由该systemd服务所起的服务或进程也会停/kill掉。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/50994
推荐阅读
相关标签
  

闽ICP备14008679号