1 |
On Friday 20 December 2013 22:07:17 Ryan Hill wrote: |
2 |
> On Tue, 17 Dec 2013 18:28:12 -0500 Mike Frysinger wrote: |
3 |
> > Use $BASHPID which will be unique even in subshells. |
4 |
> |
5 |
> This requires bash 4.0. I'm all for it, but haters gonna hate. |
6 |
|
7 |
ugh. fun fact: this is used in multiple places in portage already, as well as |
8 |
some eclasses. |
9 |
|
10 |
it can be re-implemented with: |
11 |
read -r pid _ < /proc/self/stat; echo $pid |
12 |
|
13 |
but that doesn't work in a subshell, so you couldn't do: |
14 |
bashpid() { local pid; read -r pid _ < /proc/self/stat; echo $pid; } |
15 |
echo ${BASHPID:-$(bashpid)} |
16 |
because now you'd be a sub-subshell. in this case you want the parent pid, |
17 |
but that isn't easy to get as the 2nd field of stat is the process name, and |
18 |
i'm not sure that won't have spaces (since it might be the name of the shell |
19 |
script). plus it isn't terribly portable. |
20 |
|
21 |
this seems reasonable portable though: |
22 |
bashpid() { sh -c 'echo $PPID'; } |
23 |
echo ${BASHPID:-$(bashpid)} |
24 |
even if it does have the overhead of running another bash process. but |
25 |
considering this only impacts bash-3.2, maybe we simply don't care. |
26 |
-mike |