How to shutdown Linux using C++ or Qt without call to "system()"?

Momergil picture Momergil · Mar 2, 2015 · Viewed 20.2k times · Source

I want to shutdown an Embedded Linux when a close button is pushed on the UI. I know I can do it with a call to system:

system("shutdown -P now");

Ref: Link

But knowing that using system is not advised, I'ld like to know if there is another way in C++ to do this (if there is also a specific way to do this using Qt, I'ld also like to know it although a general C++ method is more important).

Answer

tux3 picture tux3 · Mar 2, 2015

On Linux you can call the reboot system call to poweroff, halt, or reboot. The following snippet shows how to poweroff a machine, but note that it will of course only work on Linux :

#include <unistd.h>
#include <linux/reboot.h>

int main() {
    reboot(LINUX_REBOOT_MAGIC1, 
           LINUX_REBOOT_MAGIC2, 
           LINUX_REBOOT_CMD_POWER_OFF, 0);
}

Of course, you will need sufficient privileges to use this syscall.