子Shell的$$

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

  1. #!/bin/bash  
  2.   
  3. TestID()  
  4. {  
  5.         echo "in function : $$"  
  6. }  
  7.   
  8. TestID &  
  9. echo "\$! : $! "  
  10.   
  11. echo "\$\$ : $$ "  
  12. 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 shell executes 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 subshell environment to be created

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

When Bash finds such a file while searching the `$PATH’ for a command, it spawns a subshell to execute it.  In other words, executing  filename ARGUMENTS is equivalent to executing bash filename ARGUMENTS

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

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

那么这里的current shell怎么解释呢?字面意思是“当前的shell”。这里有有一篇博客讲子shell,我觉得讲的很好 http://blog.csdn.net/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。至于怎么获取,一般都用$!来获取。

再来看看下面的脚本

  1. #!/bin/bash  
  2.   
  3. echo "\$\$ outside of subshell = $$"  
  4. echo "\$BASH_SUBSHELL outside of subshell = $BASH_SUBSHELL"  
  5. echo "\$BASHPID outside of subshell = $BASHPID"  
  6. echo "-------------------"  
  7. (  
  8.         echo "\$\$ inside of subshell = $$"  
  9.         echo "\$BASH_SUBSHELL inside of subshell = $BASH_SUBSHELL"  
  10.         echo "\$BASHPID inside of subshell = $BASHPID"  
  11. )  
  12. echo "-------------------"  

$BASHPID就是指当前shell。

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

[root@fire ShellPractice]# echo $$
2618

如果你在子shell里面执行这条命令,其实是

2618echo
一直都指的的是current shell。

版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值