Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 931
Momergil Avatar asked Mar 02 '15 14:03

Momergil


People also ask

How can you shut down a Linux system?

$ sudo shutdown --halt +5 “Attention. The system is going down in five minutes.” You can also use the systemctl command to shut down the system. For example, type systemctl halt or systemctl poweroff to achieve similar results to the shutdown command.

How do you shutdown a Linux system from command line?

To shutdown Linux using the command line: To shutdown the Linux system open a terminal application. Then type “ sudo shutdown -n now ” to shutdown the box. Then wait for some time and the Linux server will poweroff.

How do I shut down C?

To shutdown immediately use "C:\\WINDOWS\\System32\\shutdown -s -t 0". To restart use "-r" instead of "-s". If you are using Turbo C Compiler then execute your program from command prompt or by opening the executable file from the folder. Press F9 to build your executable file from source program.

How can we shutdown the Linux operating system * By using halt command both halt and shutdown none of the above by using shutdown command?

shutdown Command: shutdown command used to halt, power-off or reboot the machine. halt Command: halt command used to halt, power-off or reboot the machine. poweroff Command: poweroff command used to halt, power-off or reboot the machine. reboot Command: reboot command used to halt, power-off or reboot the machine.


2 Answers

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.

like image 179
tux3 Avatar answered Sep 18 '22 17:09

tux3


Under glibc you'll need:

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

int main() {
    sync();
    reboot(LINUX_REBOOT_CMD_POWER_OFF);
}

Again, as always, you'll need to be running with sufficient privileges.

reboot's man page

like image 34
Nathan Phillips Avatar answered Sep 21 '22 17:09

Nathan Phillips