多个过程中的一个

多个过程中的一个

本文介绍了等待“多个过程中的一个".完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bash中是否有内置功能可以等待许多进程中的1个完成?然后杀死剩余的进程?

Is there any built in feature in bash to wait for 1 out of many processes to finish? And then kill remaining processes?

pids=""
# Run five concurrent processes
for i in {1..5}; do
        ( longprocess ) &
        # store PID of process
        pids+=" $!"
done

if [ "one of them finished" ]; then
        kill_rest_of_them;
fi

我正在寻找其中一个完成"命令.有吗?

I'm looking for "one of them finished" command. Is there any?

推荐答案

bash 4.3在内置的 wait -n 标志>命令,这会使脚本等待下一个子进程完成. jobs -p 选项还意味着您不需要存储pid列表,只要您不执行任何后台作业即可.'t 要等待.

bash 4.3 added a -n flag to the built-in wait command, which causes the script to wait for the next child to complete. The -p option to jobs also means you don't need to store the list of pids, as long as there aren't any background jobs that you don't want to wait on.

# Run five concurrent processes
for i in {1..5}; do
    ( longprocess ) &
done

wait -n
kill $(jobs -p)

请注意,如果除了首先完成的5个长进程之外还有另一个后台作业,则 wait -n 将在完成时退出.这也意味着您仍然想要保存要杀死的进程ID列表,而不是杀死任何 jobs -p 返回的内容.

Note that if there is another background job other than the 5 long processes that completes first, wait -n will exit when it completes. That would also mean you would still want to save the list of process ids to kill, rather than killing whatever jobs -p returns.

这篇关于等待“多个过程中的一个".完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:34