I am trying to understand why some shells seem to receive a special treatment when called with sudo. For instance, there seem to be two possible behaviours:
The "implicit" group (pstree is a direct child of sudo, no shell in between):
$ sudo pstree -s $$
systemd───login───bash───sudo───pstree
$ sudo bash -c 'pstree -s $$'
systemd───login───bash───sudo───pstree
$ sudo zsh -c 'pstree -s $$'
systemd───login───bash───sudo───pstree
$ sudo dash -c 'pstree -s $$'
systemd───login───bash───sudo───pstree
The "explicit" group (the shell is a direct child of sudo):
$ sudo ksh -c 'pstree -s $$'
systemd───login───bash───sudo───ksh───pstree
$ sudo tcsh -c 'pstree -s $$'
systemd───login───bash───sudo───tcsh───pstree
$ sudo fish -c 'pstree -s $fish_pid'
systemd───login───bash───sudo───fish───pstree
There is obviously seem to be some kind of integration happening between sudo and some shells, but I could find no documentation on it. I also grepped the source code of both sudo and bash but could find no clue there either.
This other question seems related: Why (...) doesn't spawn a new child process when run in background?
My versions of sudo and bash are:
$ sudo --version
Sudo version 1.8.29
...
$ bash --version
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
...
strace -f -e clone,fork,execve bash -c 'pstree -s $$'
would be another way to verify that it doesn't fork before exec. Your way is also solid proof, though: you're not usingstrace -f
so it's not following into child processes, but you do still see anexecve
. So it must have replaced itself. You can also see that fromstrace -f -e execve
(not displaying theclone
system call that implements fork), just from looking at the PID number if there is a fork involved at all. Tracingclone
rules out the possibility you mentioned of forking but then replacing the original. – Peter Cordes Jul 11 '22 at 11:58bash -c 'pstree -s $$ && echo foo'
to make bash fork so it can run echo or not after collecting the exit status, as a way to test a tracing method to see how it looks when a shell does fork. – Peter Cordes Jul 11 '22 at 12:01ksh
was one of the more aggressive users of various kinds of optimization, such as tail-call optimization. @Stéphane Chazelas may have more to say about that if this draws his attention. – jrw32982 Jul 13 '22 at 20:51