Get exit code of a background process

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

    This is how I solved it when I had a similar need:

    # Some function that takes a long time to process
    longprocess() {
            # Sleep up to 14 seconds
            sleep $((RANDOM % 15))
            # Randomly exit with 0 or 1
            exit $((RANDOM % 2))
    }
    
    pids=""
    # Run five concurrent processes
    for i in {1..5}; do
            ( longprocess ) &
            # store PID of process
            pids+=" $!"
    done
    
    # Wait for all processes to finish, will take max 14s
    # as it waits in order of launch, not order of finishing
    for p in $pids; do
            if wait $p; then
                    echo "Process $p success"
            else
                    echo "Process $p fail"
            fi
    done
    

提交回复
热议问题