This question may seem a bit silly, but since in Unix-based systems, replacing an executable's image is done in a single step, replacing the currently running process, in the function call execve
(and derivatives), the question is:
Why does sudo
fork()
by default before execve
'ing the replacement process?
By forking before, additional kernel elements have to be initiallized, and although fork is quite optimized in some Unices, there are still some unavoidable elements that must be initialized. If fork()
did not occur by default, the PID space would increment slower.
If you are curious, this default behaviour can be inspected by issuing a command such as
sudo sleep 30
the current code [1] is quite more complicated to follow, as many features have been added since; but in the version hosted by Apple [2] it is quite clear what it does.
#ifndef PROFILING
if ((sudo_mode & MODE_BACKGROUND) && fork() > 0)
exit(0);
else
EXEC(safe_cmnd, NewArgv); /* run the command */
#else
/* Complicated code when profiling is enabled, but we don't care */
I am currently running sudo version 1.8.11p2, and it spawns the sleep either way, with or without the -b
switch, so it seems the current code got more complicated.
I am looking for an answer which covers also why is this the default behaviour, and which advantanges it can bring us.