2

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.

0

1 Answer 1

1

$! gives the correct value.
$$ does not. Use $BASHPID instead

See man bash:

BASHPID

Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that do not require bash to be re-initialized. Assignments to BASHPID have no effect.

Not sure, why your kill -- -PID is not working, cannot reproduce. You could use pkill -P PID instead.

3
  • 1
    kill with a negative PID argument will kill a process group with that group ID. There is no process group with ID 44551 (the group is probably 44550).
    – Kusalananda
    Commented Feb 8, 2021 at 10:09
  • @Kusalananda: In light of your comment, pkill -P PID isn't equivalent to kill -- -PID, since it wouldn't terminate the children of the children. So would the only solution be to somehow create a new process group for the child function?
    – user000001
    Commented Feb 8, 2021 at 10:18
  • 1
    @user000001 This isn't a topic I'm really good at. You may want to ask a separate question about it. You current question is about the error you get and how to get the correct PID in the function, not really about how to signal all processes started from the function.
    – Kusalananda
    Commented Feb 8, 2021 at 10:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .