在退出脚本之前等待后台进程完成 [英] Waiting for background processes to finish before exiting script

查看:38
本文介绍了在退出脚本之前等待后台进程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在退出脚本 (TCL/Bash) 之前,如何确保所有后台进程都已完成执行.

How do I make sure that all my background processes have finished execution before I exit my script (TCL/Bash).

我正在考虑将我所有的后台进程 pid 写入一个 pidfile.然后在最后 pgrep pidfile 以查看在我退出之前是否有任何进程仍在运行.

I was thinking of writing all my background process pids to a pidfile. And then at the end pgrep the pidfile to see if any processes are still running before I exit.

有没有更简单的方法来做到这一点?有没有 TCL 特定的方法来做到这一点?

Is there some simpler way to do this? And is there a TCL specific way to do this?

推荐答案

如果您想等待作业完成,请使用 wait.这将使 shell 等待所有后台作业完成.但是,如果您的任何作业自己守护进程,它们就不再是 shell 的子进程并且 wait 将不起作用(就 shell 而言,子进程已经完成.确实,当一个进程自我守护程序时,它会这样做通过终止并产生一个继承其角色的新进程).

If you want to wait for jobs to finish, use wait. This will make the shell wait until all background jobs complete. However, if any of your jobs daemonize themselves, they are no longer children of the shell and wait will have no effect (as far as the shell is concerned, the child is already done. Indeed, when a process daemonizes itself, it does so by terminating and spawning a new process that inherits its role).

#!/bin/sh
{ sleep 5; echo waking up after 5 seconds; } &
{ sleep 1; echo waking up after 1 second; } &
wait
echo all jobs are done!

这篇关于在退出脚本之前等待后台进程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆