【问题标题】:Redirecting stdout & stderr from background process从后台进程重定向标准输出和标准错误
【发布时间】:2011-05-16 22:31:10
【问题描述】:

我有一个名为 foo 的脚本,它运行程序 a.exe 并将计时统计信息发送到文件 time.log

#!/bin/bash
date 1>> time.log
(time ./a.exe) 2>> time.log

如果我在终端后台运行脚本并保持外壳打开直到 a.exe 完成,则此方法有效,但如果我在后台运行脚本并退出终端(a.exe 需要很长时间才能运行)

foo & 
exit

当我回来时,a.exe 已经执行,但时间统计信息没有出现在我的日志文件中。有人知道为什么吗?关闭父外壳后,有没有办法获取计时统计信息?

谢谢

【问题讨论】:

    标签: linux bash time background stderr


    【解决方案1】:
    nohup foo &
    

    当您退出 shell 时,它会向所有子进程发送 SIGHUP 信号,默认情况下会杀死它们。如果您希望进程在父 shell 退出时继续执行,那么您需要让它忽略 SIGHUP。

    名字

    nohup -- 调用不受挂断影响的命令

    概要

    nohup utility [arg ...]
    

    说明

    nohup 实用程序使用其参数调用命令,此时将信号 SIGHUP 设置为忽略。如果标准输出是终端,标准输出将附加到当前目录中的文件 nohup.out 中。如果标准错误是一个终端,它将被定向到与标准输出相同的位置。

    【讨论】:

      【解决方案2】:

      由于问题也被标记为bash,我引用man bash

      disown [-ar] [-h] [jobspec ...]
                Without  options,  each  jobspec  is  removed  from the table of
                active jobs.  If jobspec is not present, and neither -a  nor  -r
                is  supplied, the shell's notion of the current job is used.  If
                the -h option is given, each jobspec is not removed from the ta‐
                ble,  but is marked so that SIGHUP is not sent to the job if the
                shell receives a SIGHUP.  If no jobspec is present, and  neither
                the  -a  nor the -r option is supplied, the current job is used.
                If no jobspec is supplied, the -a option means to remove or mark
                all  jobs;  the  -r  option without a jobspec argument restricts
                operation to running jobs.  The return value is 0 unless a  job‐
                spec does not specify a valid job.
      

      当您开始工作但忘记在其前加上 nohup 时,这会派上用场。做吧

      disown -ah
      disown -a
      

      【讨论】:

        【解决方案3】:

        不要忘记删除所有对 tty/pts 的引用,0/null 删除 stdin 引用。

        【讨论】:

          【解决方案4】:

          当您关闭父 shell 时,您的 a.exe 会被杀死。

          您可以键入 screen,像往常一样运行命令并退出屏幕。这可以防止进程在父 shell 退出时被终止。这种方法有点麻烦,但在其他情况下可能会很方便。

          John 给出了一个更好的答案——使用 nohup。

          【讨论】:

          • 没错。如果您事先知道您可能正在启动一个长时间运行的进程,或者您的连接不稳定,您应该使用screen 或tmux。这些程序在作业管理和窗口管理方面为您提供了更大的灵活性。
          【解决方案5】:

          试试:

          nohup <your_command> &
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-12-14
            • 2011-12-25
            • 2012-03-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-10-11
            • 2014-03-22
            相关资源
            最近更新 更多