[Bash] 等待任意进程退出的若干方法

陪她去流浪 桃子 2019年06月30日 阅读次数:4327

Bash 内置了 wait 命令用于等待进程的退出,并返回其退出码:

wait [-n] [n ...]

Wait for each specified child process and return its termination status.
Each n may be a process ID or a job specification; if a job spec is given, all processes in that job's pipeline are waited for.
If n is not given, all currently active  child  processes  are waited for, and the return status is zero.
If the -n option is supplied, wait waits for any job to terminate and returns its exit status.
If n specifies a non-existent process or job, the return status  is 127.
Otherwise, the return status is the exit status of the last process or job waited for.

但是,从说明来看,wait只能等待当前shell的子进程。如果等待的进程不是当前进程的子进程,则会报告如下错误:

$ wait 1
-bash: wait: pid 1 is not a child of this shell

但是,很多时候我们需要等待任意的进程,那么,wait就不适用了。经搜索,找到以下可用办法。

等待任意进程退出的办法

tail

用法:tail --pid=$pid -f /dev/null

**注意:**这种方法不适用于 macOS,因为其下的 tail 不支持 --pid 参数。但可以用来自 GNU 的 gtail

哈哈,可能谁也没有想到 tail 竟然还有--pid这个神奇的参数。

tail 的帮助说明:

--pid=PID
    with -f, terminate after process ID, PID dies

-f, --follow[={name|descriptor}]
    output appended data as the file grows;
    an absent option argument means 'descriptor'

lsof

用法:lsof -p $pid +r 1 &>/dev/null

lsof 用于枚举打开的文件。所以这个命令要求进程有打开文件。哪个进程那么极端会没有打开文件呢?

参考

标签:linux · 总结 · Bash · 小技巧