我通过从脚本调用进程来并行运行一些测试。 每个进程仅打印到标准输出>文件,如果成功退出 0(否则为 -1)。
如果一个进程以 -1 退出,我将一些东西打印到它(或相关)输出文件(即调用它的参数),杀死所有其他进程,然后退出。
我已经编写了一个脚本,使用 trap "..." CHLD
在子进程退出时运行一些代码,这在某些情况下有效,但我发现我的脚本不是很健壮。 如果我发送键盘中断,有时子进程会继续运行,有时子进程的数量会让机器不堪重负,而且它们似乎都没有前进。
我在我的四核笔记本电脑以及一个由 128 个 CPU 组成的集群上使用它,子进程会自动分布在这些集群上。 如何在 bash 脚本中运行大量后台子进程,仅限于其中一部分并发运行,如果其中一个返回错误代码,则执行某些操作 + 退出? 我还希望在键盘中断后清理脚本。 我应该使用 GNU-parallel 吗?如何?
这是到目前为止我的脚本的 MWE,它不受阻碍地生成子进程,并用我认为每个部分的含义进行注释。 我有使用来自 shell 的trap
的想法 - 获取后台进程的退出代码
$ cat parallel_tests.sh
#!/bin/bash
# some help from https://stackoverflow.com/questions/1570262/shell-get-exit-code-of-background-process
handle_chld() {
#echo pids are ${pids[@]}
local tmp=() ###temporary storage for pids that haven't finished
#for each pid that hadn't finished since the last trap
for((i=0;i<${#pids[@]};++i)); do
#if this pid is still running
if [[ $(ps -p ${pids[i]} -o pid=) ]]
then
tmp+=(${pids[i]}) ### add pid to list of pids that are running
else
wait ${pids[i]} ### put the exit code of this pid into $?
if [ "$?" != "0" ] ### if the exit code $? is non-zero
then
#kill all remaning processes
for((j=0;j<${#pids[@]};++j))
do
if [[ $(ps -p ${pids[j]} -o pid=) ]]
then
echo killing child processes of ${pids[j]}
pkill -P ${pids[j]}
fi
done
cat _tmp${pids[i]}
#print things to the terminal here
echo "FAILED process ${pids[i]} args: `cat _tmpargs${pids[i]}`"
exit 1
else
echo "FINISHED process ${pids[i]} args: `cat _tmpargs${pids[i]}`"
fi
fi
done
#update list of running pids
pids=(${tmp[@]})
}
# set this to monitor SIGCHLD
set -o monitor
# call handle_chld() when SIGCHLD signal is triggered
trap "handle_chld" CHLD
ALL_ARGS="2 32 87" ### ad nauseam
for A in $ALL_ARGS; do
(sleep $A; false) > _tmp$! &
pids+=($!)
echo $A > _tmpargs${pids[${#pids[@]}-1]}
echo "STARTED process ${pids[${#pids[@]}-1]} args: `cat _tmpargs${pids[${#pids[@]}-1]}`"
done
echo "Every process started. Now waiting on PIDS:"
echo ${pids[@]}
wait ${pids[@]} ###wait until every process is finished (or exit in the trap)
此版本在 2+epsilon 秒后的输出为:
$ ./parallel_tests.sh
STARTED process 66369 args: 2
STARTED process 66374 args: 32
STARTED process 66381 args: 87
Every process started. Now waiting on PIDS:
66369 66374 66381
killing child processes of 66374
./parallel_tests.sh: line 43: 66376 Terminated: 15 sleep $A
killing child processes of 66381
./parallel_tests.sh: line 43: 66383 Terminated: 15 sleep $A
FAILED process 66369 args: 2
本质上,pid 66369 首先失败,其他两个进程在陷阱中处理。 我在这里简化了测试流程的构造,因此我们不能假设我会在生成新流程之前手动插入wait
。 此外,一些测试过程几乎是即时的。 从本质上讲,我有一大堆测试过程,无论长短,只要可以分配资源就开始了。
不确定是什么导致了我上面提到的问题,因为这个脚本使用了几个对我来说是新的功能。 欢迎一般指点!
(我看过这个问题,它没有回答我的问题)
cat arguments | parallel --halt now,fail=1 my_prg
或者:
parallel --halt now,fail=1 my_prg ::: $ALL_ARGS
GNU Parallel 的设计是为了让它也会杀死远程作业。它使用远程服务器上的进程组和繁重的perl脚本来做到这一点:https://www.gnu.org/software/parallel/parallel_design.html#The-remote-system-wrapper