【问题标题】:How can I redirect process output from a process started with start-stop-daemon on Debian?如何从 Debian 上以 start-stop-daemon 启动的进程重定向进程输出?
【发布时间】:2012-09-29 01:27:05
【问题描述】:

已经有几个关于此的问题,但似乎没有一个有效。我有一个生产系统当前处于关闭状态,我需要能够快速从守护程序获取 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 脚本,但日志文件仍然为空(我知道该进程正在输出信息)。

任何帮助将不胜感激。

【问题讨论】:

  • 你不能改进你的守护进程的源代码来使用syslog(3)设施吗? AFAIK start-stop-daemon 就像 daemon(3)noclose=0 所以关闭 stdoutstderr (将它们重定向到 /dev/null
  • This 似乎工作......

标签: linux bash logging debian start-stop-daemon


【解决方案1】:

如果您有 start-stop-daemon >= 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.

【讨论】:

  • 这就是我需要的解决方案。谢谢:)
【解决方案2】:

使用> /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);
}

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

【讨论】:

    【解决方案3】:

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

    在 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 输出。

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-05
        • 2013-09-05
        • 2022-10-05
        • 2013-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多