Get pid of current subshell

后端 未结 6 798
眼角桃花
眼角桃花 2020-12-08 07:10

I am trying to get the pid of a currently executing subshell - but $$ is only returning the parent pid:

#!/usr/bin/sh

x() {
  echo \"I am a sub         


        
6条回答
  •  独厮守ぢ
    2020-12-08 07:53

    @John1024 's answer is great, but there's a little problem in there.

    when a command run like (...), the command will run in a new subprocess, so

    ( : ; bash -c 'echo $PPID' ) 
    

    will return process_id of (...), not the function's process id that call (...)

    if you want the function's process_id, you can just run:

    $SHELL -c 'echo $PPID'
    

    and the process_id will be outputed to stderr

    if you want get the function's process_id form a variable, you can run:

    $SHELL -c 'echo $PPID' | read -s func_pid
    

    then you can get the pid from variable ${func_pid}

    note: don't run this command in (...), otherwise it'll return the process_id of (...)

提交回复
热议问题