繁体   English   中英

如何在Debian上使用start-stop-daemon启动的进程重定向进程输出?

[英]How can I redirect process output from a process started with start-stop-daemon on Debian?

有几个问题已经存在,但它们似乎都没有用。 我有一个当前关闭的生产系统,我需要能够快速从守护进程获取stderr输出以进行调试。

我以为我可以直接从它被调用的点重定向输出(在init.d脚本中),但事实证明它非常困难。

 start-stop-daemon -d $DDIR -b -m --start --quiet -pidfile $PIDFILE --exec $DAEMON -- \
                $DAEMON_ARGS > /var/log/daemon.log 2>&1 \
                || return 2

这不起作用。 我尝试运行一个调用可执行文件并重定向输出的shell脚本,但日志文件仍然是空的(我确实知道该进程正在输出信息)。

任何帮助将非常感激。

如果你有start-stop-daemon> = version 1.16.5,你只需用--no-close调用它就可以重定向已启动进程的输出。

man start-stop-daemon

-C, - no-close

  Do not close any file descriptor when forcing the daemon into the background (since version 1.16.5). Used for debugging purposes to see the process output, or to redirect file descriptors to log the process output. Only relevant when using --background. 

据我所知,这是不可能的,通常当我需要从守护进程获取数据时,我要么事先记录它,要么创建一个通过网络套接字或命名管道或任何其他进程间通信机制连接到程序的监视程序。

使用> /var/log/daemon.log 2>&1调用start-stop-daemon将重定向start-stop-daemon的输出而不是启动的守护进程的输出 Start-stop-daemon将在运行守护程序之前关闭标准输出/输入描述符。

在一个简单的shell脚本中包装可执行文件:

#!/bin/bash
STDERR=$1
shift
DAEMON=$1
shift
$DAEMON 2>$STDERR $*

适合我 - 也许你应该检查文件权限?

这个天真的解决方案存在一个问题 - 当start-stop-daemon杀死这个包装器时,包装的守护进程将保持活动状态。 这在bash中无法轻易解决,因为在脚本执行期间无法运行信号处理程序(有关详细信息,请参阅trap文档)。 你必须编写一个C包装器,它看起来像这样:

#include <fcntl.h>
#include <unistd.h>
int main(int argc, char** argv){
    int fd_err;

    fd_err = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC);
    dup2(fd_err, STDERR_FILENO);
    close(fd_err);

    return execvp(argv[2], argv + 2);
}

(为清楚起见,我省略了错误检查)。

这是一个可行的解决方案(基于此处给出的解决方案)。

在init.d脚本的开头(以及标题之后),添加以下内容:

exec > >(tee --append /var/log/daemon.log)

#You may also choose to log to /var/log/messages using this:
#exec > >(logger -t MY_DAEMON_NAME)

#And redirect errors to the same file with this:
exec 2>&1

这将记录脚本期间调用的所有内容,包括start-stop-daemon输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM