简体   繁体   English

等待“许多过程中的1”完成

[英]WAIT for “1 of many process” to finish

Is there any built in feature in bash to wait for 1 out of many processes to finish? 在bash中是否有任何内置功能可以等待许多进程中的1个完成? 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 added a -n flag to the built-in wait command, which causes the script to wait for the next child to complete. bash 4.3在内置的wait命令中添加了一个-n标志,这会导致脚本等待下一个子节点完成。 The -p option to jobs also means you may not need to store don't need to store the list of pics, as long as there aren't any background jobs that you don't want to wait on. -p选项jobs也意味着你可能不需要存储并不需要存储图片列表中,只要有不是你不想等待任何后台作业。

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

wait -n
kill $(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. 请注意,如果除了首先完成的5个长进程之外还有其他后台作业,则wait -n将在完成时退出。 That would also mean you would still want to save the list of process ids to kill, rather than killing whatever jobs -p returns. 这也意味着你仍然希望保存进程ID列表以杀死,而不是杀死任何jobs -p返回。

It's actually fairly easy: 它实际上相当容易:

#!/bin/bash
set -o monitor
killAll()
{
# code to kill all child processes
}

# call function to kill all children on SIGCHLD from the first one
trap killAll SIGCHLD

# start your child processes here

# now wait for them to finish
wait

You just have to be really careful in your script to use only bash built-in commands. 您只需要在脚本中非常小心,只使用bash内置命令。 You can't start any utilities that run as a separate process after you issue the trap command - any child process exiting will send SIGCHLD - and you can't tell where it came from. 在发出trap命令后,您无法启动任何作为单独进程运行的实用程序 - 任何退出的子进程都将发送SIGCHLD - 您无法分辨它来自何处。

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

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