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

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 1
-bash: wait: pid 1 is not a child of this shell




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

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

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

tail 的帮助说明:

    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 -p $pid +r 1 &>/dev/null

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


发表于:2019年6月30日 ,阅读量:824 ,标签:linux · 总结 · Bash · 小技巧