[英]WAIT for “1 of many process” to finish
在bash中是否有任何内置功能可以等待许多进程中的1个完成? 然后杀死剩余的进程?
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
我正在寻找“其中一个完成”命令。 有没有?
bash
4.3在内置的wait
命令中添加了一个-n
标志,这会导致脚本等待下一个子节点完成。 该-p
选项jobs
也意味着你可能不需要存储并不需要存储图片列表中,只要有不是你不想等待任何后台作业。
# Run five concurrent processes
for i in {1..5}; do
( longprocess ) &
done
wait -n
kill $(jobs -p)
请注意,如果除了首先完成的5个长进程之外还有其他后台作业,则wait -n
将在完成时退出。 这也意味着你仍然希望保存进程ID列表以杀死,而不是杀死任何jobs -p
返回。
它实际上相当容易:
#!/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
您只需要在脚本中非常小心,只使用bash内置命令。 在发出trap
命令后,您无法启动任何作为单独进程运行的实用程序 - 任何退出的子进程都将发送SIGCHLD
- 您无法分辨它来自何处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.