Moin,
da mir früher schon einmal aufgefallen war, dass $$
immer die PID der startenden Shell ausgibt, habe ich einmal versucht, das systematisch anzugehen. Vielleicht habt Ihr eine Erklärung, warum $$
sich in Subshells manchmal meistens nicht ändert.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $ set -x $ pstree -Aps $$ + pstree -Aps 4139 systemd(1)---xfce4-terminal(4135)---bash(4139)---pstree(4199) $ ( pstree -Aps $$ ) + pstree -Aps 4139 systemd(1)---xfce4-terminal(4135)---bash(4139)---pstree(4200) $ ( x=1; pstree -Aps $$ ) + x=1 + pstree -Aps 4139 systemd(1)---xfce4-terminal(4135)---bash(4139)---bash(4202)---pstree(4203) $ ( x=1; pstree -Aps $(sh -c 'echo $PPID' ) ) + x=1 ++ sh -c 'echo $PPID' + pstree -Aps 4207 systemd(1)---xfce4-terminal(4135)---bash(4139)---bash(4207)---pstree(4209) $ kill -0 4207 && echo lebt + kill -0 4207 bash: kill: (4207) - No such process $ ( pstree -Aps $(sh -c 'echo $PPID' ) ) ++ sh -c 'echo $PPID' + pstree -Aps 4568 systemd(1)---xfce4-terminal(4135)---bash(4139)---pstree(4568) |
In Zeile 6 und 10 hätte ich normalerweise eine andere PID als die 4139 erwartet - mindestens in Zeile 10, denn man sieht, dass die bash
hier optimiert: wenn sich an der Umgebung (und was sonst auch noch immer) nichts ändert, ist die Subshell, die die Befehle zwischen ( ... )
ausführt, gar kein anderer Prozess. Ich hätte also eher so etwas wie Zeile 15 erwartet.
Die ganze Sache ist auch bei der bash
dokumentiert und sogar vom POSIX-Standard vorgegeben. Ich verstehe nur nicht wieso. Hat jemand einen Erklärungsansatz dafür?
PS: Noch ein interessantes Detail: in Zeilen 22 und 23 sieht man, dass die Shell keinen neuen Prozess für pstree
erzeugt, sondern sich selbst überlagert. Vermutlich ist das eine Optimierung. Das machen nicht alle so:
1 2 3 4 5 6 7 8 9 10 11 12 | $ bash -xc 'pstree -Aps $$' + pstree -Aps 4735 systemd(1)---xfce4-terminal(4135)---bash(4139)---pstree(4735) $ sh -xc 'pstree -Aps $$' + pstree -Aps 4738 systemd(1)---xfce4-terminal(4135)---bash(4139)---sh(4738)---pstree(4739) $ dash -xc 'pstree -Aps $$' + pstree -Aps 4740 systemd(1)---xfce4-terminal(4135)---bash(4139)---dash(4740)---pstree(4741) $ ksh -xc 'pstree -Aps $$' + pstree -Aps 5595 systemd(1)---xfce4-terminal(4135)---bash(4139)---pstree(5595) |
Die ksh
hier ist übrigens die aus dem Paket "ksh" - die originale AT&T ksh
in Version 93 (von 1993).