How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

后端 未结 30 2420
悲哀的现实
悲哀的现实 2020-11-22 03:50

How to wait in a bash script for several subprocesses spawned from that script to finish and return exit code !=0 when any of the subprocesses ends with code !=0 ?

S

30条回答
  •  终归单人心
    2020-11-22 04:32

    I don't believe it's possible with Bash's builtin functionality.

    You can get notification when a child exits:

    #!/bin/sh
    set -o monitor        # enable script job control
    trap 'echo "child died"' CHLD
    

    However there's no apparent way to get the child's exit status in the signal handler.

    Getting that child status is usually the job of the wait family of functions in the lower level POSIX APIs. Unfortunately Bash's support for that is limited - you can wait for one specific child process (and get its exit status) or you can wait for all of them, and always get a 0 result.

    What it appears impossible to do is the equivalent of waitpid(-1), which blocks until any child process returns.

提交回复
热议问题