I have a bash script that among other things, launches a background process. I use a function that setups some configuration for the process, launches it, checks it started correctly, and returns its PID, which is used later to kill the subprocess. The sample code below has the same structure but simplified logic:
function launcher(){
sleep 30 &
echo $!
}
PID=$(launcher)
echo $PID
kill $PID
The issue I'm facing is that the subshell that executes the launcher
function does not return until the sleep
command ends. Therefore the echo $PID
statement is not executed until the subshell ends.
what surprises me is that if I check the sleep
command, it does not have the script as parent id:
UID PID PPID C STIME TTY STAT TIME CMD
user 20135 1 0 18:39 pts/8 S+ 0:00 sleep 30
How can I start the sleep &
in the background to allow the subshell to end before it ends?
Note: Please notice in my case, the background process will never end until I kill it, so I need the subshell to end get the PID. Also notice in my real code, the logic of the launcher
function is quite complex and I'm running it as a subshell to isolate the main process from it.
Thanks in advance
It happens that the problem was about stdin
because the main shell was reading from the subshell's stdout
, which is inherited by the background process. Just redirecting the stdout
when invoking the background process makes it work as expected.
sleep 100 > /dev/null &