Kill background process when another process ends in Linux

后端 未结 1 1924
鱼传尺愫
鱼传尺愫 2021-01-26 07:11

I have a little question and I hope someone can help me because I can not find a proper solution.

I want to resolve a hostname; while waiting for the result, I\'d like

相关标签:
1条回答
  • 2021-01-26 07:29

    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!!"
    
    0 讨论(0)
提交回复
热议问题