shell 需要检查后台进程是否停止,然后添加处理器ID的Map

klsxnrf1  于 2023-02-05  发布在  Shell
关注(0)|答案(1)|浏览(155)

在我们的脚本中,我们在后台运行函数,并将它们的处理器ID存储在一个文件中,我们在一个文件中存储了6个后台处理器ID,同样我们有6个文件,每个文件有6个处理器ID。2现在我们需要检查所有这些处理器是否完成了它们的工作,以便我们可以运行另一个函数。3在无限循环中不断检查处理器是否完成了。当处理器停止时,执行处理器Map

while true; do
   for file in $(ls status); do
    while read line; do
       pgrep -x $line
    if [[ "$?" = "1" ]]; then
        log "$line is completed"
    fi
    break
    done < status/$file
    done
done

status文件夹包含文件,每个文件包含6个进程id

r6l8ljro

r6l8ljro1#

这应该行得通:

#!/usr/bin/env sh

# Fail on error
set -o errexit
# Enable wildcard character expansion
set +o noglob

# ================
# CONFIGURATION
# ================
# PID directory
PID_DIR="status"
# Sleep time in seconds
SLEEP_TIME=1

# ================
# LOGGER
# ================
# Fatal log message
fatal() {
  printf '[FATAL] %s\n' "$@" >&2
  exit 1
}

# Warning log message
warn() {
  printf '[WARN ] %s\n' "$@" >&2
}

# Info log message
info() {
  printf '[INFO ] %s\n' "$@"
}

# ================
# MAIN
# ================
{
  # Check command 'ps' exists
  command -v ps > /dev/null 2>&1 || fatal "Command 'ps' not found"
  # Check command 'sleep' exists
  command -v sleep > /dev/null 2>&1 || fatal "Command 'sleep' not found"

  # Iterate files
  for _file in "$PID_DIR"/*; do
    # Skip if not file
    [ -f "$_file" ] || continue

    info "Analyzing file '$_file'"

    # Iterate PID
    while IFS='' read -r _pid; do
      info "Analyzing PID '$_pid'"

      # Wait PID
      while true; do
        info "Checking PID '$_pid'"

        # Check PID
        if ps -p "$_pid" > /dev/null 2>&1; then
          # PID exists
          warn "PID '$_pid' not terminated. Sleeping '$SLEEP_TIME' seconds..."
          sleep "$SLEEP_TIME"
        else
          # PID not exists
          info "PID '$_pid' terminated"
          break
        fi
      done
    done < "$_file"
  done

  # PIDs terminated
  info "All PIDs terminated"

  # ...
}

备注

因为wait仅在脚本是PID的父脚本时才起作用,所以必须不断地使用ps轮询它是否存在。

相关问题