I'm writing a script that starts a subshell to go off and do some work. In a special case, the script needs to tell the subshell to cleanly stop what it's doing and exit early. However, my psuedo-code below doesn't seem to be working. Am I trying the impossible? Is it possible to define a separate trap for signals in a subshell?
#!/bin/bash
function myExitFunction { ... }
trap myExitFunction SIGTERM
while [ 1 ] ; do
waitForSpecialCondition
kill -0 $SUBSHELL_PID # check if subshell is running
if [ $? -eq 0 ] ; then # and kill it if it is
kill $SUBSHELL_PID
fi
(
someProcess
MYOWNCHILD=$! # save someProcess's pid to kill later if I need to
trap "kill $MYOWNCHILD" SIGTERM
... # do stuff
) &
SUBSHELL_PID=$!
done

( … ) &might create a subprocess of a subprocess; try{ … } &instead. Other than that, the principle looks sane. For better answers, post code that we can run and try to fix (i.e. no...or undefinedwaitForSpecialCondition). – Gilles May 24 '11 at 20:06