modifying python daemon script, stop does not retu

2019-09-18 06:09发布

问题:

Following on from the previous post, the script now start and stops the python script (and only that particular script) correctly but does not report the OK back to the screen...

USER="root"
APPNAME="myPythonApp1"
APPBIN="/usr/bin/python"
APPARGS="/usr/local/sbin/app1/app.py"
LOGFILE="/var/log/$APPNAME/error.log"
LOCKFILE="/var/lock/subsys/$APPNAME"

LOGPATH=$(dirname $LOGFILE)

prog=$APPBIN

start() {
        [ -x $prog ] || exit 5
        [ -d $LOGPATH ] || mkdir $LOGPATH
        [ -f $LOGFILE ] || touch $LOGFILE

        echo -n $"Starting $APPNAME: "
        daemon --user=$USER "$APPBIN $APPARGS >>$LOGFILE &"
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch $LOCKFILE
        return $RETVAL
}

stop() {
        echo -n $"Stopping $APPNAME: "
        pid=`ps -ef | grep "[p]ython $APPARGS" | awk '{ print $2 }'`
        echo $pid
        kill $pid
        sleep 1
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && rm -f $LOCKFILE
        return $RETVAL
}

Starting:

Starting indigolinkserver: [ OK ]

Stopping:

Stopping indigolinkserver:

Within the app.py I have added:

[...]
def set_exit_handler(func):
    signal.signal(signal.SIGTERM, func)
[...]

if __name__ == '__main__':

    def on_exit(sig, func=None):
        #print "exit handler triggered"
        sys.exit(1)

set_exit_handler(on_exit)

At command line I get the print (when uncommented) but within the daemon script I get nothing... something is not going back to RETVAL... is it fixable?

There is a post (thanks @robert) about being able only to use killproc with daemons to have this behaviour?

Thanks!

回答1:

Couldn't get it to work with the exit handlers so I ended up doing it with .pid files instead...

USER="root"
APPNAME="myPythonApp1"
APPBIN="/usr/bin/python"
APPARGS="/usr/local/sbin/app1/app.py"
LOGFILE="/var/log/$APPNAME/error.log"
LOCKFILE="/var/lock/subsys/$APPNAME"

LOGPATH=$(dirname $LOGFILE)

prog=$APPBIN

start() {
        [ -x $prog ] || exit 5
        [ -d $LOGPATH ] || mkdir $LOGPATH
        [ -f $LOGFILE ] || touch $LOGFILE

        echo -n $"Starting $APPNAME: "
        daemon --user=$USER "$APPBIN $APPARGS >>$LOGFILE &"
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch $LOCKFILE
        return $RETVAL
}

stop() {
        echo -n $"Stopping $APPNAME: "
        pid=`ps -ef | grep "[p]ython $APPARGS" | awk '{ print $2 }'`
        killproc -p /var/run/$APPNAME.pid
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && rm -f $LOCKFILE
        return $RETVAL
}

and within the python code:

if __name__ == '__main__':
    pid = str(os.getpid())
    pidfile = "/var/run/myPythonApp1.pid"

    if os.path.isfile(pidfile):
        print "%s already exists" % pidfile
        #sys.exit()
    else:
    file(pidfile, 'w').write(pid)