I have seen wrapper script examples which in a nutshell are following:
#!/bin/bash myprog=sleep echo "This is the wrapper script, it will exec "$myprog"" exec "$myprog" "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="113551">[email protected]</a>"
As seen above, they use exec to replace the newly created shell almost immediately with the $myprog. One could achieve the same without exec:
#!/bin/bash myprog=sleep echo "This is the wrapper script, it will exec "$myprog"" "$myprog" "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="022642">[email protected]</a>"
In this last example, a new bash instance is started and then $myprog is started as a child process of the bash instance.
What are the benefits of the first approach?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Using exec makes the wrapper more transparent, i.e. it makes it less likely that the user or application that calls the script needs to be aware that it’s a relay that in turns launches the “real” program.
In particular, if the caller wants to kill the program, they’ll just kill the process they just launched. If the wrapper script runs a child process, the caller would need to know that they should find out the child of the wrapper and kill that instead. The wrapper script could set a trap to relay some signals, but that wouldn’t work with SIGSTOP or SIGKILL which can’t be caught.
Calling exec also saves a bit of memory (and other resources such as PIDs etc.) since it there’s no need to keep an extra shell around with nothing left to do.
If there are multiple wrappers, the problems add up (difficulty in finding the right process to kill, memory overhead, etc.).
Some shells (e.g. the Korn shell) automatically detect when a command is the last one and there’s no active trap and put an implicit exec, but not all do (e.g. not bash).
Method 2
Finding no duplicates… refer to the FreeBSD handbook, which gives a good enough reason:
The
execstatement replaces the shell process with the specified program. Ifexecis omitted, the shell process remains in memory while the program is executing, and needlessly consumes system resources.
which is essentially the reason explained to me quite a while back (by one of the porters), and is fairly well-known.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0