0

Is it possible to put a process into the background from another background process with bash?

For instance, if we have the following code:

function check_if_server_running {
    while [ server_running -ne true ]
        curl localhost:8000
    done
    bg %-
}

check_if_server_running &
./startServer

# Some other code...

Could we replace bg %- with something to make the ./startServer run in the background once it's up? Normally bg %- puts the last process in the background but it is not working for me

1

No, that doesn't really work this way, since the bg and fg commands are only available in the interactive mode of the shell, which is definitely not the case when you're running a function or subshell in background already...

(Also, bg itself doesn't put a job that is already in background, it just resumes a stopped job in background, you need to stop the job first with Ctrl+Z.)

Consider reworking your code to start the server in background, then wait until it's running in foreground:

function wait_for_server_running {
    while ! server_running; do
        curl localhost:8000
    done
}

./startServer &
wait_for_server_running

# Some other code...

That looks similar to what you were trying to achieve, right?

5
  • Yes I was trying to do that before, but several unrelated things where blocking me from achieving that. I'll try working around that so I can start the server like that
    – User_KS
    Oct 16 '18 at 16:43
  • @User_KS Feel free to post questions about the issues you're having with the other approach, it should be easy for you to get help with that here, since it's a fairly standard approach to it. Cheers!
    – filbranden
    Oct 16 '18 at 17:03
  • thank you. I've been having this weird issue where my server does not run when it is run from the background. Theres some weird behaviour when I try to run it from the background, but usually it starts the server and immediately exits it. I'm using Play framework, which uses NettyServer for its server implementation, but it still doesn't work. I've done digging for days now and the most likely answer I could find was that theres a SIGTTIN or SIGTTOU signal being passed
    – User_KS
    Oct 16 '18 at 17:08
  • Other people have had a similar problem before: stackoverflow.com/questions/40643208/how-to-run-sbt-as-daemon
    – User_KS
    Oct 16 '18 at 17:08
  • And since Play uses TypeSafe Activator to run, which is based on SBT, that seems to be the most likely culprit. Don't know why it isn't working though
    – User_KS
    Oct 16 '18 at 17:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.