13
#!/bin/bash

function abc() # wait for some event to happen, can be terminated by other process
{
    sleep 3333 
}

echo "PID: $$"
abc &
echo "PID: $$"

I need to retrieve the pid of this function, but the echo prints the same string.

If I'm not going to put abc() out of this script, is it possible to get it's pid and terminate that function?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
daisy
  • 54,555

2 Answers2

18

You have two options, I think:

$BASHPID or $!

echo "version: $BASH_VERSION"
function abc() # wait for some event to happen, can be terminated by other process
{
          echo "inside a subshell $BASHPID" # This gives you the PID of the current instance of Bash.
          sleep 3333
}

echo "PID: $$" # (i)
abc &
echo "PID: $$" # (ii)
echo "another way $!" # This gives you the PID of the last job run in background
echo "same than (i) and (ii) $BASHPID" # This should print the same result than (i) and (ii)

sh-4.2$ ps ax|grep foo
25094 pts/13   S      0:02 vim foo.sh
25443 pts/13   S+     0:00 grep foo

sh-4.2$ ./foo.sh
version: 4.2.39(2)-release
PID: 25448
PID: 25448
another way 25449
same than (i) and (ii) 25448
inside a subshell 25449

sh-4.2$ ps ax|grep foo
25094 pts/13   S      0:02 vim foo.sh
25449 pts/13   S      0:00 /bin/bash ./foo.sh
25452 pts/13   S+     0:00 grep foo

Cheers,

Source: http://tldp.org/LDP/abs/html/internalvariables.html

nopcorn
  • 9,559
rhormaza
  • 316
  • As my test, normally $! is enough to get the single background process PID, sometimes if i run multiple background child processes (run as function following by &), it will only able to get accurate child PID with $BASHPID, especially when you want to retrieve child process itself PID inside your child process which running in background, e.g function my_func() { echo $BASHPID .... } will print accurate PID for my_func, if we run as my_func arg1 arg2 ... & – Lampard Jul 24 '20 at 01:19
4

I think you're looking for the $!

function abc() # wait for some event to happen, can be terminated by other process
{
    sleep 3333 
}

echo "PID: $$"
abc &
echo "PID: $!"
David Bain
  • 151
  • 3