Get exit code of a background process

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

    I would change your approach slightly. Rather than checking every few seconds if the command is still alive and reporting a message, have another process that reports every few seconds that the command is still running and then kill that process when the command finishes. For example:

    #!/bin/sh
    
    cmd() { sleep 5; exit 24; }
    
    cmd &   # Run the long running process
    pid=$!  # Record the pid
    
    # Spawn a process that coninually reports that the command is still running
    while echo "$(date): $pid is still running"; do sleep 1; done &
    echoer=$!
    
    # Set a trap to kill the reporter when the process finishes
    trap 'kill $echoer' 0
    
    # Wait for the process to finish
    if wait $pid; then
        echo "cmd succeeded"
    else
        echo "cmd FAILED!! (returned $?)"
    fi
    

提交回复
热议问题