1

I have a docker build script which builds a series of libraries and runs test suits. In order to make my build script run faster on a many core server, I changed put the sequential order of commands (being passed to RUN to a bash invocation of several parallel commands:

RUN /bin/bash -c -e '\
    cmd1 arg1 & \
    cmd2 & \
    cmd3 arg1 arg2=foo arg3 & \
    wait'

This worked file when there was no error. Then I realized even if one of child processes return a non-zero exit status, the whole bash command returns 0 and docker continues to build... How can I make the bash call to return 0 iff all its children return 0 ?

sorush-r
  • 10,490
  • 17
  • 89
  • 173

1 Answers1

2

You can utilize that bash's wait command for specific PID returns it's return status:

job1 &
job1pid=$!
job2 &
job2pid=$!
job3 &
job3pid=$!
if wait ${job1pid} && wait ${job2pid} && wait ${job3pid}
then
  exit 0
else
  exit 1
fi

Test:

$ cat > childprocess.sh
#!/bin/bash
awk 'BEGIN { exit('$1'); }' &
job1pid=$!
awk 'BEGIN { exit('$2'); }' &
job2pid=$!
awk 'BEGIN { exit('$3'); }' &
job3pid=$!
if wait ${job1pid} && wait ${job2pid} && wait ${job3pid}
then
  exit 0
else
  exit 1
fi

$ ./childprocess.sh 0 0 0
$ echo $?
0
$ ./childprocess.sh 1 1 1
$ echo $?
1
$ ./childprocess.sh 0 1 0
$ echo $?
1

From GNU bash doc:

wait [-n] [jobspec or pid …]

Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If the -n option is supplied, wait waits for any job to terminate and returns its exit status. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.

Kubator
  • 1,373
  • 4
  • 13