C function to shutdown linux system
Asked Answered
C

1

6

I am developing C function to shutdown my Embedded Linux system (Ubuntu) using the following way.

#include <stdlib.h>

int main() 
{
    system("shutdown -P now");
    return 0;
}

Is this approach is secure?
If not is there any better and secure way I can perform same task?

Certify answered 21/11, 2018 at 5:35 Comment(7)
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++?Ezaria
thanks got it we have to avoid system call.So how can I perform same functionality without system call?@EzariaCertify
I also read about reboot but couldn't getting it how can I use it to shutdown my system.@EzariaCertify
https://mcmap.net/q/692022/-how-to-shutdown-linux-using-c-or-qt-without-call-to-quot-system-quotEzaria
It says system("/bin/sh shutdown -P now") also safe to use Is it?@EzariaCertify
#43198176Ezaria
From the cited manpage: "Only the superuser may call reboot()." If you're not running your program as root, you may have to set the appropriate capability to it, or find another way.Garald
T
2

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.

Tineid answered 20/12, 2018 at 3:43 Comment(2)
got it thanks. but to use this we need have to use setcap cap_sys_boot+ep executabe_file @Cinder BiscuitsCertify
To shutdown instead of rebooting simply use reboot(RB_POWER_OFF);Scrutator

© 2022 - 2024 — McMap. All rights reserved.