For a large number of reasons, it is better to power off the machine using e.g.
execl("/bin/shutdown", "shutdown", "-P", "now", (char *)0);
or reboot using
execl("/bin/shutdown", "shutdown", "-r", "now", (char *)0);
There is no shell involved at all. The current process is replaced by the shutdown
system management command, which already has the necessary privileges if the user the process is running has is allowed to shutdown or reboot the machine.
(That is, code following the above statement is not executed at all, except if the system utility is missing. It will be there on any functioning system, even embedded ones.)
You can even replace the "now"
with a fixed string like "+1m"
, to shutdown or reboot after one minute has elapsed. (During that time, everything else will continue running normally. Running shutdown
with just a -c
parameter during that period will cancel the pending shutdown/reboot.)
If you do this from a GUI application, only do it where a normal program would either return
from main()
, or exit()
.
What are those reasons?
Simplicity, robustness, the principle of least surprise, proper management of privileges for shutdown/reboot, not requiring special privileges and thus reduced threat surface (bugs in your program less likely to grant special privileges, because there are none). For starters.