man reboot(2)
#include <unistd.h>
#include <sys/reboot.h>
int main () {
sync(); // If reboot() not preceded by a sync(), data will be lost.
setuid(0); // set uid to root, the running uid must already have the
// appropriate permissions to do this.
reboot(RB_AUTOBOOT); // note, this reboots the system, it's not as
return(0); // graceful as asking the init system to reboot.
}
Pre-systemd, you could also sometimes get away with:
int main() {
sync();
kill(1, SIGTERM);
return 0;
}
This method was more prevalent on embedded systems where the program is run under a single shell, but killing initd was effective as well. Note that on newer GNU/Linux's that use systemd/upstart, SIGTERM
is ignored by systemd.
system()
spawns a child process which is used to execute the command. I'd call reboot() directly. As for security please have a look at the comments to Why should the system() function be avoided in C and C++? – Ezariaroot
, you may have to set the appropriate capability to it, or find another way. – Garald