我知道在bash我们可以创建一个使用圆括号子shell (
和)
.根据bash手册页:
(list) list is executed in a subshell environment
Run Code Online (Sandbox Code Playgroud)
另外,要获取当前进程ID,我们使用:
echo $$
Run Code Online (Sandbox Code Playgroud)
现在我的问题是如何获取使用(
和)
命令行创建的子shell的进程ID ?
如果我用这个:
echo $$; ( echo $$; )
Run Code Online (Sandbox Code Playgroud)
我会在stdout上打印两次父shell的进程id,因为$$
甚至在创建subshell之前就会进行扩展.那么如何真正强迫懒惰的扩张呢?
[解决方案应该适用于Mac,而不仅仅是Linux]
建议的链接答案不起作用,因为在我的Mac上echo $BASHPID
不起作用并返回空白.
我试图获取当前正在执行的子shell的pid - 但$$
只返回父pid:
#!/usr/bin/sh
x() {
echo "I am a subshell x echo 1 and my pid is $$"
}
y() {
echo "I am a subshell y echo 1 and my pid is $$"
}
echo "I am the parent shell and my pid is $$"
x &
echo "Just launched x and the pid is $! "
y &
echo "Just launched y and the pid is $! "
wait
Run Code Online (Sandbox Code Playgroud)
产量
I am the parent shell …
Run Code Online (Sandbox Code Playgroud) 是否有可能$BASHPID
在bash3.x中获得价值?
实际上,我在bash3.x man中找不到任何关于它的描述,但它在bash4.x中可用.