PID einer aufgerufenen Funktion in der bash

Juergen Raschke mail at juergen-raschke.de
Mon Apr 5 10:10:40 CEST 2010


Hallo,

Florian Lohoff wrote:

> So geht es auch:
> 
> for i in `seq 1 4`; do sh -c "( echo $$ \$$ )" & done
> 
> Der trick ist das $$ so zu escapen das die originaere bash das dingen
> nicht expanded - die dann "geforkte" aber ... In diesem fall
> dadurch das es nicht einfach ein () ist - sondern sh -c "()" - dadurch
> kann ich fuer die geforkte shell variablen escapen ...

Es mag sich vielleicht kleinkariert anhoeren, aber dein
"escape"tes $$ liefert die pid der per sh geforkten shell
nicht der dort darin aufgerufenen subshell "()".
Das geht auch gar nicht mittels $$.


Aus "man bash":
$
Expands to the process ID of the shell. In a () subshell, it
expands to the process ID of the current shell, not the subshell.

SHLVL
Incremented by one each time an instance of bash is started.

BASH_SUBSHELL
Incremented by one each time a subshell or subshell environment
is spawned.  The initial value is 0.


BASHPID (bash v4)
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.


sh -c "echo  $$  \$$ \$BASHPID  \$SHLVL \$BASH_SUBSHELL;                     \
        ( echo $$ \$$ \$BASHPID  \$SHLVL \$BASH_SUBSHELL ) ;                  \
        ( ( echo $$ \$$ \$BASHPID \$SHLVL \$BASH_SUBSHELL ) );                \
        sh -c \" echo  $$  \\\$$ \\\$BASHPID  \\\$SHLVL \\\$BASH_SUBSHELL;    \
                ( echo $$ \\\$$ \\\$BASHPID  \\\$SHLVL \\\$BASH_SUBSHELL );\" "
18629 21949 21949 2 0
18629 21949 21950 2 1
18629 21949 21951 2 2
18629 21952 21952 3 0
18629 21952 21953 3 1






Gruss,
Juergen






More information about the Linux mailing list