Home:ALL Converter>how to use linux reboot function in C for shutdown Linux(Ubuntu) system?

how to use linux reboot function in C for shutdown Linux(Ubuntu) system?

Ask Time:2018-11-29T11:06:06         Author:raj123

Json Formatter

I am making a c program to shutdown Ubuntu without system call using following link.

code.c
#include <unistd.h>
#include <sys/reboot.h>
int main() {
reboot(RB_POWER_OFF);
}
gcc code.c -o out.exe

Here if I run this executable file(out.exe) as root user then only it will shutdown system and if I run same file in normal user mode it is not working.So what changes I have to do in my code in order to run this code in normal user mode?

Author:raj123,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53531250/how-to-use-linux-reboot-function-in-c-for-shutdown-linuxubuntu-system
Nominal Animal :

For a large number of reasons, it is better to power off the machine using e.g.\n\nexecl(\"/bin/shutdown\", \"shutdown\", \"-P\", \"now\", (char *)0);\n\n\nor reboot using\n\nexecl(\"/bin/shutdown\", \"shutdown\", \"-r\", \"now\", (char *)0);\n\n\nThere 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.\n\n(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.)\n\nYou 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.)\n\nIf you do this from a GUI application, only do it where a normal program would either return from main(), or exit().\n\n\n\nWhat are those reasons?\n\nSimplicity, 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. ",
2018-11-29T04:14:16
yy