【问题标题】:Kill background process when another process ends in Linux当另一个进程在 Linux 中结束时终止后台进程
【发布时间】:2026-01-21 23:20:03
【问题描述】:

我有一个小问题,希望有人能帮助我,因为我找不到合适的解决方案。

我想解析一个主机名;在等待结果时,如果使用 shell 脚本命令(最好是内置或普遍存在的系统命令)花费超过 30 秒,我想打印一条通知。

我有一个后台进程休眠然后打印一条消息;睡眠时,进程运行ping,但我不知道如何在 ping 完成后终止后台进程,即使 ping 在 30 秒时间限制之前结束,消息也会继续打印,因为这是更大的脚本需要一些时间才能运行。

这是我一直在使用的代码:

((sleep 30; echo "Querying the DNS server takes more than 30 seconds.") & ping -q -c 1 localhost >/dev/null)

我将不胜感激任何和所有的帮助。也欢迎其他解决方案;我只是想告诉用户DNS太慢了,这会影响进一步的执行。我试过 ping -w 或 -W 但这不是测量分辨率时间。我试图从 ping 中捕获结果。我试图用相同的 GPID 杀死所有进程,但它也在杀死控制台。我不是最好的脚本,也许这就是为什么这需要我这么多时间的原因。提前谢谢你。

【问题讨论】:

  • 这看起来像是superuser.com的问题
  • 我不明白你有什么问题。为什么说“解析一些主机名”,后来又说“ping”。
  • 当您对某个主机执行 ping 操作时,在 ping 本身之前,该主机被解析为某个 IP。我使用 ping 命令而不是 dig 或 host(它们不是核心包的一部分)来测量分辨率有多慢。
  • 此处类似情况:运行helm install --wait,同时查看分蘖的kubectl logs ...

标签: linux bash shell scripting hostname


【解决方案1】:

我希望这种方法对您有所帮助。我认为一切都非常便携,也许除了“bc”。如果你需要,我可以给你一个“bc-less”版本。祝你好运!

 #!/bin/bash

timeout=10; ## This is how long to wait before doing some batshit!
printed=1; ## this is how many times you want the message displayed (For  #instance, you might want a message EVERY X seconds)                        
starttime="$( date +%F ) $( date +%T.%3N )"

################### HERE GOES YOUR BACKGROUND PROCESS
sleep 30 &
#######################################################
processId=$!  ## And here we got the procees Id
#######################################################

while [ ! -z "$( ps -ef | grep $processId | grep -v grep )" ]
do
    endtime="$( date +%F ) $( date +%T.%3N )";
    timeelapsed=$( echo " $(date -d "$endtime" "+%s" ) - $(date -d "$starttime" "+%s" ) " | bc );
    if [[ ($timeelapsed -gt $timeout) && ($printed -ne 0) ]]
    then
            echo "This is taking more than $timeout seconds";
            printed=$(( printed - 1 ));
            starttime="$( date +%F ) $( date +%T.%3N )"
      fi
done


  ### Do something once everything finished
  echo "The background process ended!!"

【讨论】:

  • 非常感谢。我会尽快检查。看来它会完成这项工作。
  • 好兄弟。如果以后对您有用,请记住将其突出显示为正确的。 (竖起大拇指)
  • @MatiasBarrios 如果存在 pid 包含$processId 的进程,这个grep 不会返回吗?例如,如果$processId 为 1,则进程 95061 将匹配,因为 pid 中的 1。