In a Linux bash script such as:
exec /usr/lib/4.5/mono-service.exe ./AudioVideoRecorder.exe "$@"
, why do I have to exec
the command and not just run it without the exec
part?
The short answer is: you don't, but it saves about 1ms of CPU time (on modern CPUs).
(Note that you should exec
only at the end of a script, because nothing after the exec
will get run).
The longer answer is:
Exec
replaces the process image of the current process with the process image of the executable you exec.
That means that the moment you exec, the shell process that does the exec
ing gets completely destroyed and replaced by the exec
ed program.
When you don't exec
, the shell forks itself, execs in the fork, and waits around for the child process to exit, collecting its return status, in the hope there might be additional commands to run afterwards (fork
+ exec
is the standard procedure by which new commands get spawned).
Since there are none, the fork
is a complete waste of time and you might as well exec directly and save on that fork
ing time.
For most intents and purposes, it's essentially a microoptimization based on the knowledge of how process get spawned on Unices.
Note: (thanks to ilkkachu)
Where it makes a slight semantic difference is if the process spawning the script cares about how the maybe-exec'ed program dies.
If the maybe-exec'ed child exits normally, the exec and non-exec form are equivalent since the shell script forwards the last waited-on exit status to its own exit status.
If, however, the child dies from signal n
, then the shell would convert that to exit status 128+n
, effectively losing the was-signaled information.
(The information is not lost if you're sure the child never regularly exits with an exit code >128
, which is usually the case.). When you do exec, there's no middleman shell anymore, and the exit status info goes directly to the caller of the execing script (and the info about whether the child exited or was signaled is preserved, as there's no middleman shell to merge it into an exit code).
(See waitpid(2) for more information).
exec
saves one pid and some small amounts of memory required to store shell image (if there is only one left) and some process metadata about it because shell does not exist and does not wait for forked process to complete. This maybe critical in embedded systems with 16M or even 8M onboard RAM available.
exec something
vs just something
are the two options
Commented
May 30, 2016 at 9:23
exec
in shell scripts tells interpreter to replace itself with the program it runs.