Kill background process when another process ends in Linux

时光怂恿深爱的人放手 提交于 2019-12-02 10:34:28

I hope this approach helps you. I think everything is pretty much portable, except for "bc" maybe. I can give you a "bc-less" version if you need it. Good luck!

 #!/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!!"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!