If your system have systemd, then you can use logind functionality via D-Bus. Qt solution is the following (just tested):
QDBusInterface logind{"org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", QDBusConnection::systemBus()};
const auto message = logind.callWithArgumentList(QDBus::Block, "CanPowerOff", {});
QDBusPendingReply< QString > canPowerOff = message;
Q_ASSERT(canPowerOff.isFinished());
if (canPowerOff.isError()) {
const auto error = canPowerOff.error();
qWarning().noquote()
<< QDBusInterface::tr("Asynchronous call finished with error: %1 (%2)")
.arg(error.name(), error.message());
return EXIT_FAILURE;
}
if (canPowerOff.value() == "yes") {
QDBusPendingReply<> powerOff = logind.callWithArgumentList(QDBus::Block, "PowerOff", {true, });
Q_ASSERT(powerOff.isFinished());
if (powerOff.isError()) {
const auto error = powerOff.error();
qWarning().noquote()
<< QDBusInterface::tr("Asynchronous call finished with error: %1 (%2)")
.arg(error.name(), error.message());
return EXIT_FAILURE;
}
} else {
qCritical().noquote()
<< QCoreApplication::translate("poweroff", "Can't power off: CanPowerOff() result is %1")
.arg(canPowerOff.value());
return EXIT_FAILURE;
}
Also possible there is a need to add a file /etc/polkit-1/localauthority/50-local.d/10-enable-shutdown.pkla
to suppress interactive authentication requirement:
[Enable shoutdown for users]
Identity=unix-group:users
Action=org.freedesktop.login1;org.freedesktop.login1.power-off;org.freedesktop.login1.power-off-ignore-inhibit;org.freedesktop.login1.power-off-multiple-sessions
ResultAny=yes
ResultInactive=yes
ResultActive=yes
system()
not advised? – PittsburghQDBus
api I think. – Sucrasesystem()
almost always represents a security problem. – Sucrase