linux - shell - get exit code of background process -
i have command cmd called main bourne shell script takes forever.
i want modify script follows:
- run command cmd in parallel background process ($cmd &).
- in main script, have loop monitor spawned command every few seconds. loop echoes messages stdout indicating progress of script.
- exit loop when spawned command terminates.
- capture , report exit code of spawned process.
can give me pointers accomplish this?
1: in bash, $!
holds pid of last background process executed. tell process monitor, anyway.
4: wait <n>
waits until process id complete (it block until process completes, might not want call until sure process done). after wait
returns, exit code of process returned in variable $?
2, 3: ps
or ps | grep " $! "
can tell whether process still running. how understand output , decide how close finishing. (ps | grep
isn't idiot-proof. if have time can come more robust way tell whether process still running).
here's skeleton script:
# simulate long process have identifiable exit code (sleep 15 ; /bin/false) & my_pid=$! while ps | grep " $my_pid " # might need | grep -v grep here echo $my_pid still in ps output. must still running. sleep 3 done echo oh, looks process done. wait $my_pid my_status=$? echo exit status of process $my_status