Reputation: 634
I am developing a C function to shutdown my Embedded Linux system (Ubuntu) using the following code:
#include <stdlib.h>
int main()
{
system("shutdown -P now");
return 0;
}
Is this approach secure?
If not is there any better and secure way I can perform same task?
Upvotes: 7
Views: 2703
Reputation: 5261
#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.
Upvotes: 3