2

I'm trying to run background tasks in Codebuild using the nohup command as described in the document (https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-background-tasks.html)

Below is the buildspec I'm using

version: 0.2 
phases:   
  build:
    commands:
      - nohup sleep 30 & echo $! > pidfile 
      - wait $(cat pidfile)

I get an error for this as below

[Container] 2021/08/25 06:04:40 Running command wait $(cat pidfile)
/codebuild/output/tmp/script.sh: line 4: wait: pid 207 is not a child of this shell

[Container] 2021/08/25 06:04:40 Command did not exit successfully wait $(cat pidfile) exit status 127
[Container] 2021/08/25 06:04:40 Phase complete: BUILD State: FAILED

I do not understand why the wait command i being executed in a different shell. Is there any way how I can make this execute in the same shell or am I doing it wrong?

Bhargav Mg
  • 337
  • 4
  • 12

1 Answers1

1

I experienced the same, sometimes wait doesn't work in CodeBuild.

I found an answer here that might explain the issue.

There can be workarounds to replace wait:

  • poll the PID until it exists, e.g.: while [ -e /proc/$PID ]; do sleep 1; done (from here), or you can also use ps --pid $PID > /dev/null or kill -0 $PID 2>/dev/null or some other solutions to determine whether the background process finished

  • copy the stdout file descriptor of the command to a custom one, and read from that until it is closed:

exec 3< <(sleep 3 2>&1)  
...  
cat <&3  # print the output of the background process and will wait until it exits

A big limitation of these is that the exit code of the background process is unknown (wait would return with that). You have to save it somewhere if you need it.

Tovask
  • 21
  • 1