linux - 即使子进程仍在运行,Bash 等待子进程也可以返回

标签 linux bash shell

我有一个 shell 脚本,它在后台生成一个子进程并等待它(通过 wait 命令)。它还捕获 SIGTERM 并将其传递给 child 。但是每当我向父进程发送 SIGTERM 时,即使 child 仍在运行( child 捕获 SIGTERM),它也会从“等待”中退出。是否有可能在 shell 脚本中实现真正等待 child 直到 child 死亡?

最佳答案

这是常见习语所依赖的显式行为。请注意以下区别:

# this waits 10 seconds, and doesn't handle signal handlers until later
sleep 10

# this returns immediately when a signal is received
sleep 10 & wait $!

您完全可以检查是否存在剩余的后台任务并再次等待:

sleep 10 & pid=$!
while kill -0 "$pid"; do wait "$pid"; done

有关信号处理的完整讨论,包括此处描述的行为,请参阅 SignalTrap .

关于linux - 即使子进程仍在运行,Bash 等待子进程也可以返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41582738/

相关文章:

linux - 如何在 bash 脚本中读取文件时删除 1 个或多个匹配行

linux - 如何将 expect 与可选提示一起使用?

linux - Bash History Expansion 可以用于引用同一命令中的某些内容吗?

linux - 将 Java 输出存储到文件

shell - 如何在接收端打开一个没有 SSHD 的 shell?

shell - 使 : Capture output of shell command and return code at same time

java - 为什么 Java 安全点从未达到?线程挂起,安全点超时

linux - 使用 telegram-cli 时将大括号 "{}"插入到消息文本中

linux - 在 Linux C shell 上使用向上箭头显示最后一个命令

linux - Grep/Sed/Awk 修剪特定列中 IP 地址周围的文本以仅保留 IP 本身?