I am trying to capture the PID of a function executed in the background, but I seem to get the wrong number.
See the following script:
$ cat test1.sh
#!/bin/bash
set -x
child() {
echo "Child thinks is $$"
sleep 5m
}
child &
child_pid="$!"
echo "Parent thinks pid $child_pid"
sleep 3
kill -- -"$child_pid" # but it is wrong, get "No such process"
kill -- -"$$"
wait
I would expect the parent to terminate the child process of the function, but I get:
$ ./test1.sh
+ child_pid=44551
+ echo 'Parent thinks pid 44551'
Parent thinks pid 44551
+ sleep 3
+ child
+ echo 'Child thinks is 44550'
Child thinks is 44550
+ sleep 5m
+ kill -- -44551
./test1.sh: line 15: kill: (-44551) - No such process
+ kill -- -44550
Terminated
I have read this question Get PID of a function executed in the background, but the answers seem to contradict what I am observing.
So how can I fix the above code, to get the correct PID of the function from the parent?
After some testing it seems that the command without the minus works
kill -- "$child_pid"
But this isn't sufficient for my need, because I want to terminate any subprocesses of child
too when I kill it.