$$在子shell脚本VS $$ [英] $$ in a script vs $$ in a subshell
问题描述
$$给出脚本进程的进程ID在脚本中使用时,是这样的:
$$ gives process id of the script process when used in a script, like this:
例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
请遵守$$给出的PID和PS是的 15326
我的shell提示符是PID的 15073
My shell prompt is pid 15073
但在子shell,$$给父shell(即15073)
But in a subshell, $$ gives pid of parent shell ( which is 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
下面子shell为PID 15340
Here subshell is pid 15340
问:为什么呢?是不是剧本也处于子shell运行?例如什么2子shell和外壳在该脚本示例1中运行之间的区别?
Question: Why so ? Isn't the script also running in a subshell ? Whats the difference between the subshell in example 2 and the shell in which the script runs in example 1 ?
推荐答案
我试过和逃避(传递给$$子shell)作为子shell继承父猛砸$$值不起作用。解决这个问题的解决方法是使用$ BASHPID。
I tried and escaping (to pass the $$ to the subshell) does not work as the subshell inherits the $$ value from the parent bash. The solution to this is to use $BASHPID.
(echo $$; echo $BASHPID)
从父shell和子shell打印PID。
prints the PID from the parent shell and from the subshell.
这篇关于$$在子shell脚本VS $$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!