在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
Run Code Online (Sandbox Code Playgroud)
我正在寻找"其中一个完成"命令.有没有?
bash4.3 -n为内置wait命令添加了一个标志,这会导致脚本等待下一个子进程完成.该-p选项jobs也意味着你可能不需要存储并不需要存储图片列表中,只要有没有你任何后台作业不希望等待.
# Run five concurrent processes
for i in {1..5}; do
( longprocess ) &
done
wait -n
kill $(jobs -p)
Run Code Online (Sandbox Code Playgroud)
请注意,如果除了首先完成的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
Run Code Online (Sandbox Code Playgroud)
您只需要在脚本中非常小心,仅使用bash内置命令即可。发出命令后,您将无法启动作为单独进程运行的任何实用程序trap-退出的所有子进程都会发送SIGCHLD-并且您无法确定其来源。
| 归档时间: |
|
| 查看次数: |
2336 次 |
| 最近记录: |