Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

bash - $$ in a script vs $$ in a subshell

$$ gives process id of the script process when used in a script, like this:

Example 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

Observe the pid given by $$ and ps is 15326

My shell prompt is pid 15073

But in a subshell, $$ gives pid of parent shell (which is 15073)

Example 2

$ ( ps -o cmd,pid,ppid ; echo $$ )
CMD                           PID  PPID
bash                        15073  4657
bash                        15340 15073
ps -o cmd,pid,ppid          15341 15340
15073

Here subshell is pid 15340

Question: Why so? Isn't the script also running in a subshell? What's the difference between the subshell in example 2 and the shell in which the script runs in example 1?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

prints the PID from the parent shell and from the subshell.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...