如何并行执行一次包含 20 个不同变量的脚本?

如何并行执行一次包含 20 个不同变量的脚本?

我尝试files使用 warc.sh 一次运行 20 个,或者更确切地说是同时运行 20 个 warc.sh 实例,并将目录内容作为输入。我还尝试监视 PID,以防发生不好的事情,并且每次旧实例终止时都使用新输入加载新实例。

# test if files exists and run
if [ "$(ls -A ${base_dir}/schedule)" ]; then

    # function to be backgrounded
    track()
    {
      ./warc "${base_dir}/schedule/$1 printf" "\nFinished: %d\n" "$1"
    }

    start=$(date '+%s')

    # Make an associative array in which you'll record pids.
    declare -A pids

    # Background an instance of the track() function for each number, record the pid.
    for n in `ls -A ${base_dir}/schedule`; do
        if [ ${#pids[@]} > 20 ]; then
          track $n &
          pid=$!
          echo "Backgrounded: $n (pid=$pid)"
          pids[$pid]=$n
        else
            echo 'Sleeping' ; sleep 2
        fi
    done

    # Watch your stable of backgrounded processes.
    # If a pid goes away, remove it from the array.
    while [ -n "${pids[*]}" ]; do
      sleep 1
      for pid in "${!pids[@]}"; do
        if ! ps "$pid" >/dev/null; then
          unset pids[$pid]
          echo "unset: $pid"
        fi
      done
      if [ -z "${!pids[*]}" ]; then
        break
      fi
      printf "\rStill waiting for: %s ... " "${pids[*]}"
    done

    printf "\r%-25s \n" "Done."
fi

现在,这个问题已经完全失控,并产生了 900 多个后台进程 =/

答案1

编写Makefile并运行make -j 20
你可以用 shell 脚本编写 Makefile

相关内容