获取后台执行的函数的PID

dai*_*isy 11 bash process background-process

#!/bin/bash

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

echo "PID: $$"
abc &
echo "PID: $$"
Run Code Online (Sandbox Code Playgroud)

我需要检索pid此函数的 ,但回显打印相同的字符串。

如果我不打算abc()退出此脚本,是否可以获取它pid并终止该功能?

小智 16

你有两种选择,我认为:

$BASHPID 或者 $!

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
Run Code Online (Sandbox Code Playgroud)

干杯,

资料来源:http : //tldp.org/LDP/abs/html/internalvariables.html