Bash has $$and variables $BASHPIDthat are somewhat confusing. $$is the process id of the script itself. $BASHPIDis the process identifier of the current Bash instance. These things are not the same, but often give the same results. In your case, you used it incorrectly. Replacing $$with $BASHPIDin functions foowill solve the problem.
See Bash Internal Variables Advanced Scripting Guide for more details.
user405725
source
share