繁体   English   中英

如何在shell中的多个进程下获得正确的尾部PID

[英]How to get correct tail PID under multiple process in shell

我正在实现monitor_log函数,它将monitor_log运行日志的最新行并使用 while 循环检查所需的字符串,超时逻辑应该是当尾日志运行超过 300 秒时,它必须关闭尾和 while 循环管道。 请参阅如何在 shell 上正确超时尾管道,如前所述,即使monitor_log函数完成,它也会在后台留下tail进程,所以我必须手动杀死它,以防数百次调用monitor_log会留下数百个tail进程。

下面的函数monitor_log只在单进程情况下杀死正确的tail PID,因为tail_pid=$(ps -ef | grep 'tail' | cut -d' ' -f5)将返回正确的tail PID,它在唯一的进程上。 当遇到多进程情况(进程分叉)时,例如多次调用monitor_log函数并行尾日志,就会有多个tail进程在运行, tail_pid=$(ps -ef | grep 'tail' | cut -d' ' -f5)无法准确返回属于当前分叉的tail PID。

那么当monitor_log功能完成时,是否可以离开tail进程? 或者,如果离开tail进程,是否有正确的方法来找到其正确的PID(不是来自其他线程的tail PID)并在多进程情况下杀死它?

function monitor_log() {
  if [[ -f "running.log" ]]; then
    # Tail the running log last line and keep check required string
    while read -t 300 tail_line
    do
      if [[ "$tail_line" == "required string" ]]; then
        capture_flag=1
      fi
      if [[ $capture_flag -eq 1 ]]; then
        break;
      fi
    done < <(tail -n 1 -f "running.log")
    # Not get correct tail PID under multiple process
    tail_pid=$(ps -ef | grep 'tail' | cut -d' ' -f5)
    kill -13 $tail_pid
  fi
}

你可以试试下面的代码:

function monitor_log() {
  if [[ -f "running.log" ]]; then
    # Tail the running log last line and keep check required string
    while read -t 300 tail_line
    do
      if [[ "$tail_line" == "required string" ]]; then
        capture_flag=1
      fi
      if [[ $capture_flag -eq 1 ]]; then
        break;
      fi
    done < <(tail -n 1 -f "running.log")

     tailpid=$!

     kill $tailpid
  fi
}

> $! 给出在后台运行的最后作业的进程 ID (PID)

更新:这将杀死触发尾部的子shell,如评论中所建议的

另一种方法可能是向 tail 命令添加超时,如下所示:

timeout 300s tail -n 1 -f "running.log"

暂无
暂无

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

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