2

I'm trying to find out how to background a process in a script that calls another function and reliably terminate it when ready. Will I have to move it all into one function?

function dosomething {
    while :
    do
    printsomething "doing something"
    done
}

function printsomething {
    echo $@
}

function otherfunction {
    dosomething &
    TMP_PID=$!
}

function killsomething {
    quit_test=`ps -p "$TMP_PID" | sed '1d' | awk '{print $1}'`
    if [ "$quit_test" != "" ] ; then
        (kill $TMP_PID >/dev/null)
    fi
}

## MAIN

    TMP_PID=""
    echo "starting program"
    otherfunction
    sleep 5s
    killsomething
  • Not very clear on what youre trying to accomplish, however you can call functions from a backgrounded function without issues. Unless you do another background call from within the first background call, theres no reason it wont work. Have you tried it? – Patrick Dec 23 '11 at 6:57
  • yeah, its doing some strange things and ultimately wont stop. – lolfrog Dec 23 '11 at 7:01
  • your example works fine, please post something that actually fails so I can debug. – Samus_ Dec 25 '11 at 20:57
  • oh and you don't need to initialize variables. – Samus_ Dec 25 '11 at 20:57
  • It's never a bad idea to initialize variable. This is particularly relevant to variables whose first use is inside a function; depending on the shell and function definition (function f{} vs f(){}), the variable's scope may be limited to the function otherwise. – dannysauer Feb 26 '14 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.