子shell的$$
来源:互联网 发布:sql语句语法检查工具 编辑:程序博客网 时间:2024/04/29 18:35
下面是一段代码,我偶然发现有点问题。
#!/bin/bashTestID(){ 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 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 shell, not 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。至于怎么获取,一般都用$!来获取。
再来看看下面的脚本
#!/bin/bashecho "\$\$ 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。
- 子shell的$$
- 子shell的$$
- 子Shell的$$
- 子shell
- 子shell
- 【linux学习】--子shell的相关概念
- 3.shell变量的子串应用
- SHELL文件夹及其子文件夹的遍历
- 进入子shell的各种情况分析
- 进入子shell的各种情况分析
- Linux 的 Shell 子Shell 作业管理 进程管理
- 父Shell与子Shell
- 父Shell与子Shell
- Shell及 子Shell关系
- 父shell和子shell的区别,在shell脚本中要cd一个文件夹为什么要用父shell运行
- shell变量的子串的删除/替换
- shell变量的子串的截取/删除/替换
- (管道)写入子shell
- 又一经典音乐,不说了,你懂得
- 哲学与实践:如何使用有个性的员工
- 从 VC7 的 CHtmlView 不能正常退出谈 CComPtr 使用中的一个误区
- 网页中嵌套youku视频
- 如何閱讀學術論文 - 選擇要閱讀的論文 (Deciding what to read)
- 子shell的$$
- 奶瓶(beini) 又一蹭网神器 1.2.2增强版带600万密码字典
- struts2 strus.xml中result类型及含义
- Farewell, My dear friend
- CView::OnMouseActivate这个方法有点问题
- 第七周实验报告任务1
- 展讯平台如何调试之assert的串口打印
- android 单元测试以及debug调试代码查看变量
- 一日一点RakNet(31)--Autopatcher