为什么我的类似守护程序的Python脚本运行多次?

时间:2019-04-18 21:56:50

标签: python raspberry-pi

我使用/etc/init.d(或停止)从sudo /etc/init.d/fanservice.sh start中的bash脚本启动Python脚本

它按预期方式启动和停止,并在启动时启动。 Python脚本运行良好。

但是,在tophtop中,我看到该脚本正在运行多次。

可能是什么原因导致的,如何停止? 除了寻找其他触发器之外(我已经检查了crontab中的脚本没有旧的引用),我不确定还有什么地方可以找到。

这是/etc/init.d/fanservice.sh

我以root身份运行Python脚本,以允许访问GPIO。

#!/bin/sh

### BEGIN INIT INFO
# Provides:          myservice
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Put a short description of the service here
# Description:       Put a long description of the service here
### END INIT INFO

# Change the next 3 lines to suit where you install your script and what you want to call it
DIR=/home/pi
DAEMON=$DIR/fanservice.py
DAEMON_NAME=fanservice

# Add any command line options for your daemon here
DAEMON_OPTS=""

# This next line determines what user the script runs as.
# Root generally not recommended but necessary if you are using the Raspberry Pi GPIO from Python.
DAEMON_USER=root

# The process ID of the script when it runs is stored here:
PIDFILE=/var/run/$DAEMON_NAME.pid

. /lib/lsb/init-functions

do_start () {
    log_daemon_msg "Starting system $DAEMON_NAME daemon"
    start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS
    log_end_msg $?
}
do_stop () {
    log_daemon_msg "Stopping system $DAEMON_NAME daemon"
    start-stop-daemon --stop --pidfile $PIDFILE --retry 10
    log_end_msg $?
}

case "$1" in

    start|stop)
        do_${1}
        ;;

    restart|reload|force-reload)
        do_stop
        do_start
        ;;

    status)
        status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
        ;;

    *)
        echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
        exit 1
        ;;

esac
exit 0

Python脚本使用wireingPi,GPIO,tach和Paho.mqtt读取温度,设置风扇速度,从转速中读取速度,然后将MQTT消息发送给代理。全部包含在True:循环中,最后以time.sleep(58)循环,因此我期望的是“服务”每58秒启动并循环一次。

它会执行此操作,但每分钟左右都会有一个新实例出现在顶部。

如果我检查/var/run/fanservice.pid的脚本PID的存储位置,就会发现它具有第一个实例的PID。

例如,在15或20分钟后,htop将显示脚本运行的PID与存储在PID文件中的PID匹配,并且自启动以来,该过程的时间为XX分秒。然后将有XX个重复的进程,这些进程具有自己的PID,所有进程的时间均为00:00.00,它们的数量(我认为)与自启动以来的分钟数相对应。

任何提示都非常欢迎。 init.d脚本是我在互联网上找到的,不记得在哪里-但是我认为我可能已经以某种方式破坏了它!就是说,我转而使用计时器循环而不是cron运行这些任务,因为Python脚本在被cron调用后没有退出。我还以这种方式运行其他脚本,这些脚本需要比距cron最少1分钟更快的循环,所以我想学习如何使其正常工作。

谢谢!

0 个答案:

没有答案