本文介绍了如何等待脚本产生的所有子(和孙子等)进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:

用户向我提供他们要运行的自定义脚本.这些脚本可以是任何类型的脚本,例如启动多个 GUI 程序、后端服务的脚本.我无法控制脚本的编写方式.这些脚本可以是阻塞类型,即执行等待直到所有子进程(顺序运行的程序)退出

Users provide me their custom scripts to run. These scripts can be of any sort like scripts to start multiple GUI programs, backend services. I have no control over how the scripts are written. These scripts can be of blocking type i.e. execution waits till all the child processes (programs that are run sequentially) exit

#exaple of blocking script
echo "START"
first_program
second_program
echo "DONE"

或非阻塞类型,即在后台 fork 子进程并退出类似的东西

or non blocking type i.e. ones that fork child process in the background and exit something like

#example of non-blocking script
echo "START"
first_program &
second_program &
echo "DONE"

我想达到什么目的?

用户提供的脚本可以是上述两种类型中的任何一种,也可以是两者的混合.我的工作是运行脚本并等待它启动的所有进程退出,然后关闭节点.如果它是阻塞类型,情况很简单,即获取脚本执行进程的 PID 并等待 ps -ef|grep -ef PID 没有更多条目.非阻塞脚本给我带来了麻烦

User provided scripts can be of any of the above two types or mix of both. My job is to run the script and wait till all the processes started by it exit and then shutdown the node. If its of blocking type, case is plain simple i.e. get the PID of script execution process and wait till ps -ef|grep -ef PID has no more entries. Non-blocking scripts are the ones giving me trouble

有什么方法可以获取由执行脚本产生的所有子进程的 PID 列表?任何指针或提示将不胜感激

Is there a way I can get list of PIDs of all the child process spawned by execution of a script? Any pointers or hints will be highly appreciated

推荐答案

您可以使用 wait 等待所有由 userscript 启动的后台进程完成.由于 wait 仅适用于当前 shell 的子进程,因此您需要获取它们的脚本,而不是将其作为单独的进程运行.

You can use wait to wait for all the background processes started by userscript to complete. Since wait only works on children of the current shell, you'll need to source their script instead of running it as a separate process.

( source userscript; wait )

在显式子 shell 中获取脚本应该足够接近地模拟启动一个新进程.如果没有,您还可以将子 shell 设为后台,这会强制启动一个新进程,然后等待 it 完成.

Sourcing the script in an explicit subshell should simulate starting a new process closely enough. If not, you can also background the subshell, which forces a new process to be started, then wait for it to complete.

( source userscript; wait ) & wait

这篇关于如何等待脚本产生的所有子(和孙子等)进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:16