简体   繁体   中英

Why a background process forces the parent to exit when background process exits with status 1?

My Bash code :

#!/bin/sh
set -ex
function func ()
{
    sleep $1
        echo $1
if [ $1 -eq 10 ]; then
 exit 1
fi
}

func 10 &
pid_a=$!
func 5 &
pid_b=$!
func 3 &
pid_c=$!
wait $pid_b
if [ $? -eq 0 ];then echo "b.ksh SUCCESS"; else echo "b.ksh FAILED"; fi
wait $pid_c
if [ $? -eq 0 ];then echo "c.ksh SUCCESS"; else echo "c.ksh FAILED"; fi
wait $pid_a
if [ $? -eq 0 ];then
echo "a.ksh SUCCESS"; else echo "a.ksh FAILED"; fi

When it is run with set -ex enabled:

sh-4.2$ ./ex.sh 
+ pid_a=16341
+ func 10
+ pid_b=16342
+ sleep 10
+ func 5
+ pid_c=16343
+ sleep 5
+ wait 16341
+ func 3
+ sleep 3
+ echo 3
3
+ '[' 3 -eq 10 ']'
+ echo 5
5
+ '[' 5 -eq 10 ']'
+ echo 10
10
+ '[' 10 -eq 10 ']'
+ exit 1

Here parent also exited along with background process that exited with status 1. Can you explain why?

You cannot do

command
if [ $? -eq 0 ]; then ...

in a set -e -using script. The script will end because of the nonzero exit status of command before it even gets to the if .

And wait reports the exit status of the waited-on process as its own exit status (orherwise the $? check would be pointless anyway). Try this instead:

if wait $pid_x; then
 echo "x.ksh SUCCESS"
else
 echo "x.ksh FAILED"
fi

The manual for bash says of set -e :

-e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or || list, or if the command's return value is being inverted via ! . A trap on ERR, if set, is executed before the shell exits.

It doesn't say anything about 'when a background process exits with a non-zero status, the shell will not terminate' — so it did terminate when the background process failed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM