How can I add a 'shutdown option' to my program?
Or how can I send commands to terminal from my program (so I can send a sudo shutdown
command) ?
Planning to write in c++.
You can use system()
function defined in the header stdlib.h
.
#include<stdlib.h>
int main()
{
system("dbus-send --system --print-reply --dest=org.freedesktop.login1 /org/freedesktop/login1 \"org.freedesktop.login1.Manager.PowerOff\" boolean:true");
retrun 0;
}
This is advised over sudo shutdown
because the former does not require root privileges. Or your program will ask for the administrative password before shutdown.
You can get more information about the system command from it's manpage:
man system
… how can I send commands to terminal from my program …
Using system
, eg:
#include <stdio.h>
#include <stdlib.h>
int main() {
system("/bin/ls -la");
}
or
#include <stdio.h>
#include <stdlib.h>
int main() {
system("sudo shutdown");
}
Example
% gcc foo.cpp
% ./a.out
[sudo] password for aboettger:
% cat foo.cpp
#include <stdio.h>
#include <stdlib.h>
int main() {
system("sudo shutdown");
}