如何在后台等待后台作业?

如何在后台等待后台作业?

我有以下问题:

$ some_command &     # Adds a new job as a background process
$ wait && echo Foo   # Blocks until some_command is finished
$ wait && echo Foo & # Is started as a background job and is done immediately

我想做的wait &是在后台等待,直到所有其他后台作业完成了。

我有什么办法可以实现这一目标吗?

答案1

在某些时候,某些东西必须等待命令的执行。
但是,如果您可以将命令放在几个函数中,则可以安排它们执行您需要的操作:

some_command(){
    sleep 3
    echo "I am done $SECONDS"
}

other_commands(){
    # A list of all the other commands that need to be executed
    sleep 5
    echo "I have finished my tasks $SECONDS"
}

some_command &                      # First command as background job.
SECONDS=0                           # Count from here the seconds.
bg_pid=$!                           # store the background job pid.
echo "one $!"                       # Print that number.
other_commands &                    # Start other commands immediately.
wait $bg_pid && echo "Foo $SECONDS" # Waits for some_command to finish.
wait                                # Wait for all other background jobs.
echo "end of it all $SECONDS"       # all background jobs have ended.

如果睡眠时间如代码 3 和 5 所示,则 some_command 将在其余作业之前结束,并且将在执行时打印:

one 760
I am done 3
Foo 3
I have finished my tasks 5
end of it all 5

如果睡眠时间为(例如)8 和 5,则将打印以下内容:

one 766
I have finished my tasks 5
I am done 8
Foo 8
end of it all 8

注意顺序。事实上,每个部分都已尽可能结束($SECONDS打印的价值)。

相关内容