shell 为什么$$返回与父进程相同的id?

js4nwp54  于 2022-11-16  发布在  Shell
关注(0)|答案(8)|浏览(180)

我对巴斯有意见,我也不知道为什么.
在shell下,我输入:

echo $$    ## print 2433
(echo $$)  ## also print 2433
(./getpid) ## print 2602

其中getpid是一个C程序,用于获取当前的 pid,例如:

int main() {
    printf("%d", (int)getpid());
    return 0;
   }

令我困惑的是:
1.我认为“(命令)”是一个子进程(我说的对吗?),我认为它的 pid 应该与它的 * 父pid* 不同,但它们是相同的,为什么...
1.当我用我的程序在括号中显示 pid 时,它显示的 pid 是不同的,对吗?

  1. $$是类似宏的东西吗?
    你能帮我吗?
gc0ot86w

gc0ot86w1#

$$被定义为返回子shell中父进程的进程ID;从手册页的“特殊参数”下:
$扩展到shell的进程ID。在()子shell中,它扩展到当前shell的进程ID,而不是子shell。
bash 4中,您可以使用BASHPID获取子进程的进程ID。

~ $ echo $$
17601
~ $ ( echo $$; echo $BASHPID )
17601
17634
c6ubokkw

c6ubokkw2#

您可以使用下列其中一项。

  • $!是最后一个后台进程的PID。
  • kill -0 $PID检查它是否仍在运行。
  • $$是当前shell的PID。
krcsximq

krcsximq3#

1.括号调用一个subshell in Bash。因为它只是一个subshell,它可能有相同的PID -取决于实现。
1.您调用的C程序是一个单独的进程,它有自己唯一的PID --不管它是否在子shell中。

  1. $$是Bash中当前脚本PID的别名。请在此处查看$$$BASHPID之间的区别,以及其上包含嵌套级别的附加变量$BASH_SUBSHELL
pod7payv

pod7payv4#

如果您希望C程序打印shell的PID,请尝试getppid()

aiqt4smr

aiqt4smr5#

这是获得正确PID一种通用方法
pid=$(cut -d' ' -f4 < /proc/self/stat)
同样的方法也适用于sub

SUB(){
    pid=$(cut -d' ' -f4 < /proc/self/stat)
    echo "$$ != $pid"
}

echo "pid = $$"

(SUB)

校验输出

pid = 8099
8099 != 8100
sycxhyv7

sycxhyv76#

如果您询问如何获取一个已知命令的PID,它将类似于以下内容:
如果您已发出以下命令#发出的命令是***
如果=/dev/diskx属于=/dev/disky,则添加dd

则您可以用途:

PIDs=$(ps | grep dd | grep if | cut -b 1-5)

这里所发生的是它将所有需要的唯一字符传输到一个字段,并且可以使用
回显$PID

e0uiprwp

e0uiprwp7#

如果您需要一个简单的shell脚本来获取带有变量的最大PID,请执行以下操作

pid=$(cat /proc/sys/kernel/pid_max)
echo $pid

打印出最大PID值。

pprl5pva

pprl5pva8#

实现这一目标的便携方式

get_own_pid() {
  # This function being called in a subshell,
  # it must returns the pid of the parent of the "cut" command parent
  cut -d' ' -f4 < /proc/self/stat \
    | xargs -I% sh -c 'cut -d" " -f4 < /proc/%/stat'
}

get_parent_pid() {
  # Same thing but repeating the last command once more to get the parent one level above
  cut -d' ' -f4 < /proc/self/stat \
    | xargs -I% sh -c 'cut -d" " -f4 < /proc/%/stat' \
    | xargs -I% sh -c 'cut -d" " -f4 < /proc/%/stat'
}

# Here pid is the same as the $$ pid because called from main process
MY_PID=$(get_own_pid)
echo "$$ == ${MY_PID}"

# Here called in a subprocess, the returned pid is different
(
  MY_CHILD_PID=$(get_own_pid)
  PARENT_PID_FROM_CHILD=$(get_parent_pid)
  echo "$$ != ${MY_CHILD_PID}"
  echo "$$ == ${PARENT_PID_FROM_CHILD}"
)

灵感来自artem lapkin answer,谢谢!

相关问题