python linux服务_Python脚本作为linux服务/守护进程

你好

我试图让python脚本在(ubuntu)linux上作为服务(守护进程)运行。

在web上有几种解决方案,如:A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. A DaemonContext instance holds the behaviour and configured process environment for the program; use the instance as a context manager to enter a daemon state.

不过,由于我想将python脚本与ubuntu linux集成在一起,所以我的解决方案是与init.d脚本的组合#!/bin/bash

WORK_DIR="/var/lib/foo"

DAEMON="/usr/bin/python"

ARGS="/opt/foo/linux_service.py"

PIDFILE="/var/run/foo.pid"

USER="foo"

case "$1" in

start)

echo "Starting server"

mkdir -p "$WORK_DIR"

/sbin/start-stop-daemon --start --pidfile $PIDFILE \

--user $USER --group $USER \

-b --make-pidfile \

--chuid $USER \

--exec $DAEMON $ARGS

;;

stop)

echo "Stopping server"

/sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose

;;

*)

echo "Usage: /etc/init.d/$USER {start|stop}"

exit 1

;;

esac

exit 0

在python中:import signal

import time

import multiprocessing

stop_event = multiprocessing.Event()

def stop(signum, frame):

stop_event.set()

signal.signal(signal.SIGTERM, stop)

if __name__ == '__main__':

while not stop_event.is_set():

time.sleep(3)

我现在的问题是这种方法是否正确。我需要处理任何额外的信号吗?它会是一个“性能良好的Unix守护进程”吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值