How to restart Linux from inside a C++ program?

Dave K picture Dave K · Apr 20, 2010 · Viewed 27.3k times · Source

I have a Qt 4 GUI where I need to have a option in a drop-down menu that allows the user to choose to restart the computer. I realize this might seem redunant with the ability to restart the computer in other ways, but the choice needs to stay there. I've tried using system() to call the following:

  1. a suid-root shell script
  2. a non-suid shell script
  3. a suid-root binary program

and all of them just cause

reboot: must be superuser
to be printed. Using system() to call reboot directly does the same thing. I'm not especially attached to using system() to do this, but it seemed like the most direct choice.

How can I reboot the system from the GUI?

Answer

Vilhelm Gray picture Vilhelm Gray · Sep 12, 2013

The reboot function is described in the Linux Programmer's Manual. Under glibc, you can pass the RB_AUTOBOOT macro constant to perform the reboot.

Note that if reboot is not preceded by a call to sync, data may be lost.

Using glibc in Linux:

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

sync();
reboot(RB_AUTOBOOT);