我试图获取当前正在执行的子shell的pid - 但$$只返回父pid:
#!/usr/bin/sh
x() {
echo "I am a subshell x echo 1 and my pid is $$"
}
y() {
echo "I am a subshell y echo 1 and my pid is $$"
}
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
Run Code Online (Sandbox Code Playgroud)
产量
I am the parent shell …Run Code Online (Sandbox Code Playgroud) $$ 在脚本中使用时给出脚本进程的进程ID,如下所示:
例1
#!/bin/bash
# processid.sh
# print process ids
ps -o cmd,pid,ppid
echo "The value of \$\$ is $$"
$ ./processid.sh
CMD PID PPID
bash 15073 4657
/bin/bash ./processid.sh 15326 15073
ps -o cmd,pid,ppid 15327 15326
The value of $$ is 15326
Run Code Online (Sandbox Code Playgroud)
观察PID给出$$并且ps是15326
我的shell提示符是pid 15073
但在子shell中,$$给出父shell的pid(15073)
例2
$ ( ps -o cmd,pid,ppid ; echo $$ )
CMD PID PPID
bash 15073 4657
bash 15340 15073
ps -o cmd,pid,ppid 15341 15340
15073
Run Code Online (Sandbox Code Playgroud)
这里的子shell是pid …