wait

There is a way of making sure the script doesn't finish before alice does: the built-in command wait. Without arguments, wait simply waits until all background jobs have finished. So to make sure the above code behaves properly, we would add wait, like this:

alice &
hatter
wait

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Here, if hatter finishes first, the parent shell will wait for alice to finish before finishing itself.

If your script has more than one background job and you need to wait for specific ones to finish, you can give wait the process ID of the job.

However, you will probably find that wait without arguments suffices for all coroutines you will ever program. Situations in which you would need to wait for specific background jobs are quite complex and beyond the scope of this book.