Get exit code of a background process

前端 未结 12 1737
别跟我提以往
别跟我提以往 2020-11-22 17:14

I have a command CMD called from my main bourne shell script that takes forever.

I want to modify the script as follows:

  1. Run the command CMD in parallel
12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 18:02

    Our team had the same need with a remote SSH-executed script which was timing out after 25 minutes of inactivity. Here is a solution with the monitoring loop checking the background process every second, but printing only every 10 minutes to suppress an inactivity timeout.

    long_running.sh & 
    pid=$!
    
    # Wait on a background job completion. Query status every 10 minutes.
    declare -i elapsed=0
    # `ps -p ${pid}` works on macOS and CentOS. On both OSes `ps ${pid}` works as well.
    while ps -p ${pid} >/dev/null; do
      sleep 1
      if ((++elapsed % 600 == 0)); then
        echo "Waiting for the completion of the main script. $((elapsed / 60))m and counting ..."
      fi
    done
    
    # Return the exit code of the terminated background process. This works in Bash 4.4 despite what Bash docs say:
    # "If neither jobspec nor pid specifies an active child process of the shell, the return status is 127."
    wait ${pid}
    

提交回复
热议问题