Raghuram Vadapalli
Raghuram Vadapalli

Reputation: 1240

Send a running function to background in bash

As the title says, I want to send a running function to the background. Something like

function myfunc {
    some_command | while read line
    #some_command must be running indefinitely
    do
        #if some condition on ${line} satisfies
        #Do something and go to background
    done
}

Is it possible?

I know that it is possible to call a function directly & to directly run it in the background. That is pretty obvious. This is not duplicate of this.

Upvotes: 4

Views: 885

Answers (1)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

A simple command creates a process in background and waits for its termination, in your case the caller must continue when a condition is met asynchronously with callee which continues running.

This can be done with kill -STOP (caller blocks himself) and kill -CONT (callee unblock caller)

function myfunc {
    some_command | while read line
    #some_command must be running indefinitely
    do
        #if some condition on ${line} satisfies
        kill -CONT $$
    done & kill -STOP $$
}

Upvotes: 4

Related Questions