Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Question says it all on the tin. Can someone explain to me what goes on here ? I'm trying to find out how to background a process in a script that calls another function and reliably terminate it when ready. Wondering whether I will 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
share|improve this question
    
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 at 15:13
add comment

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.