子shell的$$

本文通过实例探讨了Shell脚本中子进程ID($!)与当前进程ID($$)的区别及联系,详细解释了不同场景下子shell的创建方式,并通过特殊变量展示了子shell与父shell之间的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是一段代码,我偶然发现有点问题。

#!/bin/bash

TestID()
{
        echo "in function : $$"
}

TestID &
echo "\$! : $! "

echo "\$\$ : $$ "
sleep 1

[firefox@fire ShellPractice]$ ./stopped.sh
$! : 15021
$$ : 15020
in function : 15020

疑问就是在这里,$!代表是最后一个后台程序的ID,$$是当前进程ID,而&出来的应该是一个子shell,但是它的ID(在子shell里这时候是$$打印出来的)和父shell是“一样”的。我去论坛上问了下,然后查了些资料。下面是一些简单的介绍:


shell什么情况下会产生子进程

1:&,提交后台作业

If a command is terminated by the control operator `&’, the shellexecutes the command asynchronously in a subshell.

2:管道

Each command in a pipeline is executed in its own subshell

3:括号命令列表

()操作符

Placing a list of commands between parentheses causes a subshellenvironment to be created

4:执行外部脚本、程序:

When Bash finds such a file whilesearching the `$PATH’ for a command, it spawns a subshell to executeit.In other words, executing filename ARGUMENTSis equivalent to executingbash filename ARGUMENTS

再看看man bash里面对于$的解释

“$” Expands to the process ID of the shell. In a () subshell, it expands to the process ID of thecurrent shell,not the sub‐shell.

那么这里的current shell怎么解释呢?字面意思是“当前的shell”。这里有有一篇博客讲子shell,我觉得讲的很好http://blog.youkuaiyun.com/sosodream/article/details/5683515。用 ./xxx.sh 执行脚本的时候也会生成子shell,原来的shell会有一个 ID,这里假设叫ID1,然后进入脚本,这时脚本里的$$就是current shell的ID(由ID1生出的子shell的ID)之后再生出其余的子shell的$$都是current shell的ID,也就是由ID1生出来的ID,注意:子shell的ID可不是$$。子shell有它自己的ID。至于怎么获取,一般都用$!来获取。

再来看看下面的脚本

#!/bin/bash

echo "\$\$ outside of subshell = $$"
echo "\$BASH_SUBSHELL outside of subshell = $BASH_SUBSHELL"
echo "\$BASHPID outside of subshell = $BASHPID"
echo "-------------------"
(
        echo "\$\$ inside of subshell = $$"
        echo "\$BASH_SUBSHELL inside of subshell = $BASH_SUBSHELL"
        echo "\$BASHPID inside of subshell = $BASHPID"
)
echo "-------------------"

$BASHPID就是指当前shell。

现在再来看看 man bash 中“$”的解释

[root@fire ShellPractice]# echo $$
2618

如果你在子shell里面执行这条命令,其实是$$先替换为2618,然后再进行echo,$$一直都指的的是current shell。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值