1

I have a list of processes triggered one after the other, in parallel. And, I need to know the exit code of all of these processes when they complete execution, without waiting for all of the processes to finish.

While status=$?; echo $status would provide the exit code for the last command executed, how do I know the exit code of any completed process, knowing the process id?

Arun George
  • 1,167
  • 3
  • 15
  • 29
  • Thanks for the pointer. The solution is good, when we can wait for all the processes to terminate, sequentially. But in this case, I need to know the exit status without waiting for processes to terminate. For eg, what was the exit code for the first (fastest) completed pid. – Arun George Aug 21 '20 at 15:50
  • Launch them with a wrapper that does whatever you want with the exit code when the process completes (for example, writing it to file "winner" and killing the rest). – stark Aug 21 '20 at 16:05
  • This needs more details, and some code. I didn't understand what you're asking here. Do you want to retrieve exit status of the job that completes the earliest? – oguz ismail Aug 21 '20 at 19:23
  • You can't know the exit status of a process without waiting for it to *finish*. – Paul Hodges Aug 21 '20 at 20:16

2 Answers2

1

You can do that with GNU Parallel like this:

parallel --halt=now,done=1 ::: ./job1 ./job2 ./job3

The --halt=now,done=1 means halt immediately, as soon as any one job is done, killing all outstanding jobs immediately and exiting itself with the exit status of the complete job.

There are options to exit on success, or on failure as well as by completion. The number of successful, failing or complete jobs can be given as a percentage too. See documentation here.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
0

Save the background job id using a wrapper shell function. After that the exit status of each job can be queried:

#!/bin/bash

jobs=()

function run_child() {
    "$@" &
    jobs+=($!)
}

run_child sleep 1
run_child sleep 2
run_child false

for job in ${jobs[@]}; do
    wait $job
    echo Exit Code $?
done

Output:

Exit Code 0
Exit Code 0
Exit Code 1
Jürgen Hötzel
  • 18,997
  • 3
  • 42
  • 58