Get pid of current subshell

后端 未结 6 814
眼角桃花
眼角桃花 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:44

    Environment:

    SUSE Linux Enterprise Server 10 SP2 (i586)

    GNU bash, version 3.1.17(1)-release (i586-suse-linux) Copyright (C) 2005 Free Software Foundation, Inc.

    #!/usr/bin/sh
    
    x() {
      mypid=$(awk 'BEGIN {print PROCINFO["ppid"] ; exit}')
      echo "I am a subshell x echo 1 and my pid is $mypid"
    }
    
    y() {
      mypid=$(awk 'BEGIN {print PROCINFO["ppid"] ; exit}')
      echo "I am a subshell y echo 1 and my pid is $mypid"
    }
    
    
    echo "I am the parent shell and my pid is $$"
    x &
    echo "Just launched x and the pid is $! "
    
    y &
    echo "Just launched y and the pid is $! "
    
    wait
    

    Result:

    I am the parent shell and my pid is 27645
    Just launched x and the pid is 27646
    Just launched y and the pid is 27647
    I am a subshell y echo 1 and my pid is 27647
    I am a subshell x echo 1 and my pid is 27646
    

提交回复
热议问题