I'm trying to use some functions in a bash script to simplify calling some child processes. I want to decide at the call site whether or not to run the process in the background as a job, or in the foreground, and later kill the child process when necessary. Unfortunately, as far as I can tell, the pid I get with $! doesn't belong to the long-running background process, but the function that called it. Killing the pid I get with $! doesn't kill the long running child process, and it seems to get orphaned.
function inner() {
tail -f /dev/null
}
function outer() {
inner
}
outer &
echo 'Before, $!: ' $!
echo 'Before, jobs -p: ' $(jobs -p)
echo 'Before, ps aux: ' $(ps aux | grep /dev/null | grep -v grep)
kill $!
echo 'After, $!: ' $!
echo 'After, jobs -p: ' $(jobs -p)
echo 'After, ps aux: ' $(ps aux | grep /dev/null | grep -v grep)
The output I get is:
Before, $!: 71644
Before, jobs -p: 71644
Before, ps aux: jstaab 71646 0.0 0.0 4267744 688 s005 S+ 2:53PM 0:00.00 tail -f /dev/null
After, $!: 71644
After, jobs -p: 71644
./test.sh: line 17: 71644 Terminated: 15 outer
After, ps aux: jstaab 71646 0.4 0.0 4267744 688 s005 S+ 2:53PM 0:00.00 tail -f /dev/null
You'll notice that ps aux gives me a different pid than either $! or jobs -p. This makes sense, but how can I kill tail -f /dev/null with a kill without grepping for the command?