Shell wait builtin, lost children

This is probably something that's rehashed every now and then.

Pitfalls in shell's handling of asynch processes.

Four children are launched. They exit out of order:
Code:
 $ cat k
for i in 2 4 3 1
do
        (sleep $i; exit $i) &
done

for i in 1 2 3 4
do
        wait %$i
        echo $i exit $?
done
$ sh k
1 exit 2
2 exit 4
3 exit 127
4 exit 1
$ ksh k
1 exit 2
2 exit 4
3 exit 127
4 exit 127
Both sh(1) and shells/pdksh (v5.2.14.2) lose some of the children. Using no frills 10.3-RELEASE-p7 i386, fully idle during the test.

sh can be fixed with the interactive-flag, but it gets talkative:
Code:
 $ sh -i k
1 exit 2
2 exit 4
3 exit 3
4 exit 1
[1]   Done(2)                 (sleep ${i}; exit ${i})
[2]   Done(4)                 (sleep ${i}; exit ${i})
[3]   Done(3)                 (sleep ${i}; exit ${i})
[4]   Done(1)                 (sleep ${i}; exit ${i})
ksh cannot be fixed with ksh -m, you have to intrude into the script, but it stays quiety.
Code:
set -m

for i in 2 4 3 1
do
    (sleep $i; exit $i) &
...
Code:
 $ ksh k
1 exit 2
2 exit 4
3 exit 3
4 exit 1

Are there better fixes ? How other shells fare ?

JAFO,
Juha
 
In this particular case, it seems to behave like pdksh.

Thanks for the tip. Collecting courage to change to using it.
Juha
 
Back
Top