4

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.

9
  • Possible duplicate of executing shell command in background from script Commented Jul 24, 2017 at 15:19
  • 1
    Why are you trying to do this? You can call your function form a separated bash script an call this with an ampersand. Then your function is run in the background. Commented Jul 24, 2017 at 15:21
  • Why not while true; do if ...; then do_something & break; fi Commented Jul 24, 2017 at 15:31
  • @WilliamPursell I edited the question. Now it should be clear why I am asking. Commented Jul 24, 2017 at 15:39
  • I don't know if you can send a function to the background. But you surely can send a process or the script to the background. You just need to send an SIGSTOP signal. Commented Jul 24, 2017 at 15:45

1 Answer 1

4

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 $$ } 
Sign up to request clarification or add additional context in comments.

1 Comment

FYI, the function keyword makes this code needlessly noncompliant with the POSIX sh specification -- it would be portable to a wider array of shells if the first line were myfunc() {, with the function keyword removed and the () syntax added.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.