Bash-将标准输出和错误输出重定向到后台进程的文件中

3

我已经为正在构建的应用程序创建了一个简单的init脚本。脚本的开始部分如下:

user="ec2-user"

name=`basename $0`
pid_file="/var/run/python_worker.pid"
stdout_log="/var/log/worker/worker.log"
stderr_log="/var/log/worker/worker.err"

get_pid() {
    cat "$pid_file"
}

is_running() {
    [ -f "$pid_file" ] && ps `get_pid` > /dev/null 2>&1
}

case "$1" in
    start)
    if is_running; then
        echo "Already started"
    else
        echo "Starting $name"
        cd /var/lib/worker
        . venv/bin/activate
        . /etc/profile.d/worker.sh
        python run.py  >> "$stdout_log" 2>> "$stderr_log" &
        echo $! > "$pid_file" 
        if ! is_running; then
            echo "Unable to start, see $stdout_log and $stderr_log"
            exit 1
        fi
        echo "$name running"
    fi

我遇到了这行代码的问题:

python run.py  >> "$stdout_log" 2>> "$stderr_log" &

我希望用以下代码启动我的应用程序,并将输出重定向到上面指定的文件。但是,当我加入&使其在后台运行时,两个日志文件中都没有任何内容。但是,当我从此行中删除&时,日志文件会得到数据。为什么会这样?
显然,我需要运行该命令以使其作为后台进程运行,以停止shell等待。
我也确定使用&时该进程正在运行。我可以通过ps -aux找到它:
root     11357  7.0  3.1 474832 31828 pts/1    Sl   21:22   0:00 python run.py

有人知道我哪里做错了吗?:)
1个回答

6

有人知道我哪里做错了吗?:)

简短回答:

是的。在python命令中添加-u,它应该可以工作。

python -u run.py  >> "$stdout_log" 2>> "$stderr_log" &

长答案:

这是一个缓冲问题(来自man python):

   -u     Force stdin, stdout and stderr to be totally unbuffered.  On systems where it matters, also put stdin, stdout
          and  stderr  in  binary  mode.   Note that there is internal buffering in xreadlines(), readlines() and file-
          object iterators ("for line in sys.stdin") which is not influenced by this option.  To work around this,  you
          will want to use "sys.stdin.readline()" inside a "while 1:" loop.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接