相关疑难解决方法(0)

获取当前子shell的pid

我试图获取当前正在执行的子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)

bash sh

26
推荐指数
2
解决办法
1万
查看次数

在脚本中的$$ vs子shell中的$$

$$ 在脚本中使用时给出脚本进程的进程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给出$$并且ps15326

我的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 …

bash shell scripting

11
推荐指数
3
解决办法
8425
查看次数

标签 统计

bash ×2

scripting ×1

sh ×1

shell ×1