Get exit code of a background process

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

    Another solution is to monitor processes via the proc filesystem (safer than ps/grep combo); when you start a process it has a corresponding folder in /proc/$pid, so the solution could be

    #!/bin/bash
    ....
    doSomething &
    local pid=$!
    while [ -d /proc/$pid ]; do # While directory exists, the process is running
        doSomethingElse
        ....
    else # when directory is removed from /proc, process has ended
        wait $pid
        local exit_status=$?
    done
    ....
    

    Now you can use the $exit_status variable however you like.

提交回复
热议问题