3

I have a script containing two functions. one function starts the other as a background process and returns that processes UID. This works well, as long as I don't want to put the PID into a dedicated variable. Once I try to assign the PID to a variable, the script hangs until the background operation finishes.

This behaviour can be demonstrated by the following script:

#!/bin/sh

foo () {
    bar &   # start bar in background
    echo $! # return bars' PID
}

bar () {
    sleep 5 # some background operation
}

FOO=$(foo) # remember the PID of bar
echo $FOO  # expectation: should echo immediately
           # reality: echo after five seconds

So, my question is: How can I get the script to continue executing after starting the bar function, without waiting for bar to return?

3

The subshell started by $(foo) has to exit completely (along with any background processes), so that the main shell knows there's no further input coming to be captured by the command substitution. After all, bar could output something after the sleep.

But you could redirect the output of bar to /dev/null:

foo () { 
    bar > /dev/null &
    echo "$!"
}

Or (in Bash or ksh) nix the command substitution and run bar in the main shell:

foo() {
    typeset -n _pid=$1
    bar &
    _pid=$!
}
foo FOO
echo "$FOO"

(Or the equivalent with eval in standard sh.)

0

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.