-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
79 lines (62 loc) · 2.51 KB
/
main.cpp
File metadata and controls
79 lines (62 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QProcess>
#include <unistd.h>
int main(int argc, char *argv[]) {
// Check if running as root
if (getuid() != 0) {
QProcess process;
QStringList args;
// Use the absolute path to the executable
// argv[0] might be relative, so we use /proc/self/exe to get the real path
// if possible, or just rely on argv[0] if we trust it. Ideally
// QCoreApplication::applicationFilePath() but we need a QCoreApplication
// instance first.
// Let's create a temp QApplication just to get the path, or use argv[0]
// carefully. Actually, we can just create QApplication first.
QApplication a(argc, argv);
QString exePath = QCoreApplication::applicationFilePath();
args << exePath;
// pkexec requires the command to be passed as arguments
// We simply run: pkexec <path_to_executable>
// However, we shouldn't continue the non-root instance.
// We can try to execute pkexec replacing the current process, or start it
// and exit.
// Using execvp to replace current process is cleaner but harder with Qt
// args. Let's just start QProcess and exit.
// Note: pkexec might not be installed on all systems, but it's standard on
// most desktop Linux.
// We need to detach or wait? If we wait, we block.
// Better to just run and exit.
// Construct command: pkexec /path/to/exe
// We don't pass other args for now as we don't use them.
// IMPORTANT: We must NOT create the MainWindow if we are just redirecting.
// Re-implementation with clean logic:
// 1. Create App
// 2. Check root
// 3. If not root, spawn pkexec and exit.
qDebug() << "Not running as root. Relaunching with pkexec...";
// We use system() or exec() family to replace process to keep terminal
// attached if any, but QProcess::startDetached is easier for GUI apps.
QString command = "pkexec";
QStringList arguments;
arguments << "env";
arguments << QString("DISPLAY=%1").arg(qgetenv("DISPLAY"));
arguments << QString("XAUTHORITY=%1").arg(qgetenv("XAUTHORITY"));
arguments << exePath;
if (QProcess::startDetached(command, arguments)) {
return 0;
} else {
qDebug() << "Failed to launch pkexec.";
// Fallthrough to run as non-root (might fail later) or show error?
// Let's fallthrough but user knows it might fail.
}
} else {
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
return 0;
}