WAIT for “1 of many process” to finish

扶醉桌前 提交于 2019-12-10 14:05:00

问题


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?


回答1:


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)

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.




回答2:


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. 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.



来源:https://stackoverflow.com/questions/37620703/wait-for-1-of-many-process-to-finish

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!