Get exit code of a background process

前端 未结 12 1929
别跟我提以往
别跟我提以往 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:01

    This may be extending beyond your question, however if you're concerned about the length of time processes are running for, you may be interested in checking the status of running background processes after an interval of time. It's easy enough to check which child PIDs are still running using pgrep -P $$, however I came up with the following solution to check the exit status of those PIDs that have already expired:

    cmd1() { sleep 5; exit 24; }
    cmd2() { sleep 10; exit 0; }
    
    pids=()
    cmd1 & pids+=("$!")
    cmd2 & pids+=("$!")
    
    lasttimeout=0
    for timeout in 2 7 11; do
      echo -n "interval-$timeout: "
      sleep $((timeout-lasttimeout))
    
      # you can only wait on a pid once
      remainingpids=()
      for pid in ${pids[*]}; do
         if ! ps -p $pid >/dev/null ; then
            wait $pid
            echo -n "pid-$pid:exited($?); "
         else
            echo -n "pid-$pid:running; "
            remainingpids+=("$pid")
         fi
      done
      pids=( ${remainingpids[*]} )
    
      lasttimeout=$timeout
      echo
    done
    

    which outputs:

    interval-2: pid-28083:running; pid-28084:running; 
    interval-7: pid-28083:exited(24); pid-28084:running; 
    interval-11: pid-28084:exited(0); 
    

    Note: You could change $pids to a string variable rather than array to simplify things if you like.

提交回复
热议问题