【问题标题】:Add output to another process running from cron将输出添加到从 cron 运行的另一个进程
【发布时间】:2021-06-30 17:46:37
【问题描述】:

我看到很多关于从另一个进程获取输出的问题。这个问题正好相反:注入另一个进程的 STDOUT。

我每天都有一个 cron 作业(一个 Bash 脚本执行 rsync 备份)。在某些情况下,它会运行超过 24 小时。所以第二天,在再次开始备份之前,我的脚本会检查昨天的备份是否仍在运行。如果是,则脚本kills 启动前未完成备份。

我想要在终止昨天的 cron 作业之前在输出中添加一行,以便发送的电子邮件 cron 将在输出中包含一行解释发生的事情。

当我终止我的 cron 作业时,我们收到的电子邮件中的输出以

结尾
/bin/sh: line 1: 132887 Terminated              /usr/local/bin/backup-to-external

我希望 cron 的电子邮件(也)包含类似的内容

Backup was still running. Terminating it before starting it again.

【问题讨论】:

    标签: linux bash cron pty


    【解决方案1】:

    您可以更新 cronjob 以执行 bash 脚本(如果它已经不是)。在脚本中,编写一个信号处理程序来输出您的消息并终止您的进程。像下面这样,

    #!/usr/bin/env bash
    
    if [[ -f "/path/to/my/binary.pid" ]]; then
        already_running_pid=$(cat "/path/to/my/binary.pid")
        echo "I'm new ($$). Terminating old."
        kill -15 $already_running_pid
        wait $already_running_pid
    fi
    
    /path/to/your/binary <some args> &
    my_binary_pid=$!
    echo $$ > /path/to/my/binary.pid
    
    function stop_services() {
      kill -9 $my_binary_pid
      echo "I'm old ($$). Being Terminated."
    }
    
    trap stop_services SIGTERM
    wait
    rm /path/to/my/binary.pid
    

    你的 cron 应该运行这个 bash 脚本,而不是你的 /path/to/your/binary。

    【讨论】:

      猜你喜欢
      • 2021-03-28
      • 2023-01-26
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 2012-03-07
      • 2012-10-08
      相关资源
      最近更新 更多