Linux start-stop-daemon 目录调用 shell/python 脚本时出错



我刚刚熟悉Linux,由于目录问题,我似乎无法获得运行python脚本的start-stop-daemon。在 linux 文件结构中,我有这些文件:

~/测试.txt

THIS LINE IS A TEST

~/test.py

#!/usr/bin/python
import time
with open("test.txt") as f:
    while True:
        try:
            print("Hello World")
            print(f.readline())
            time.sleep(2) 
        except KeyboardInterrupt:
            f.close()
            break

~/test.sh

#!/bin/bash
echo "SHELL SCRIPT SUCCESS" > /var/log/test.log
cd ~/
./test.py > /var/log/test.log

从任何目录调用sudo bash ~/test.sh.log测试将按预期填充源自 test.py 的 stdout。出于某种原因,启动以下 start-stop-daemon 服务脚本将生成一个测试.log但不填充 stdout:

/

etc/init.d/test

#!/bin/sh
### BEGIN INIT INFO
# Provides:     Python test script
# Required-Start:   $remote_fs $syslog
# Required-Stop:    $remote_fs $syslog
# Default-Start:    2 3 4 5
# Default-Stop:     0 1 6
# Short-Description:    Prints out daemonized argument
# Description:      Creates output of argument
### END INIT INFO
DAEMON_DIR=/home/alex
DAEMON=$DAEMON_DIR/test.sh
DAEMON_NAME=test
DAEMON_OPTS="hello"
DAEMON_USER=root
PYTHON=/usr/bin/python
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 --exec $PYTHON --startas $DAEMON 
    start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --chuid $DAEMON_USER --startas /bin/bash  /home/alex/test.sh
    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

这是可以在start-stop-daemon内解决的目录问题吗?或者,我对可以通过冷启动(即没有cron作业(保留的其他脚本服务方法持开放

态度

尝试使用绝对路径调用cd,例如/home/alexjg/而不是~/; 它之前被破坏的原因是,在您的示例中,您使用的是sudo,它使运行它的用户的主目录保持运行。但是,当您从 init 调用 bash 脚本时,它将使用 root 的主目录,而不是不包含 test.py 的 .

创建该文件是因为重定向仍然成功;但是,由于启动 Python 失败,因此没有输出。

最新更新