Activate the target graphical session instead of rebooting, so a KDE or GNOME session stays alive while another one is used. Switching relies on logind VT activation, which needs no root privileges and never restarts the display manager.
108 lines
2.5 KiB
C++
108 lines
2.5 KiB
C++
#include "process.h"
|
|
|
|
#include <sys/types.h>
|
|
#include <sys/wait.h>
|
|
#include <unistd.h>
|
|
|
|
#include <cerrno>
|
|
#include <cstdlib>
|
|
#include <sstream>
|
|
|
|
namespace fws {
|
|
|
|
CommandResult runCommand(const std::vector<std::string>& arguments) {
|
|
CommandResult result;
|
|
if (arguments.empty()) {
|
|
return result;
|
|
}
|
|
|
|
int pipeFds[2];
|
|
if (pipe(pipeFds) != 0) {
|
|
return result;
|
|
}
|
|
|
|
const pid_t pid = fork();
|
|
if (pid < 0) {
|
|
close(pipeFds[0]);
|
|
close(pipeFds[1]);
|
|
return result;
|
|
}
|
|
|
|
if (pid == 0) {
|
|
close(pipeFds[0]);
|
|
dup2(pipeFds[1], STDOUT_FILENO);
|
|
dup2(pipeFds[1], STDERR_FILENO);
|
|
close(pipeFds[1]);
|
|
|
|
std::vector<char*> argv;
|
|
argv.reserve(arguments.size() + 1);
|
|
for (const std::string& argument : arguments) {
|
|
argv.push_back(const_cast<char*>(argument.c_str()));
|
|
}
|
|
argv.push_back(nullptr);
|
|
|
|
execvp(argv[0], argv.data());
|
|
_exit(127);
|
|
}
|
|
|
|
close(pipeFds[1]);
|
|
char buffer[4096];
|
|
ssize_t count = 0;
|
|
while ((count = read(pipeFds[0], buffer, sizeof(buffer))) > 0) {
|
|
result.output.append(buffer, static_cast<std::size_t>(count));
|
|
}
|
|
close(pipeFds[0]);
|
|
|
|
int status = 0;
|
|
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
|
|
}
|
|
|
|
result.started = true;
|
|
result.exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
|
|
return result;
|
|
}
|
|
|
|
std::string findExecutable(const std::string& name) {
|
|
const char* pathVariable = std::getenv("PATH");
|
|
if (pathVariable == nullptr) {
|
|
return {};
|
|
}
|
|
|
|
std::istringstream stream(pathVariable);
|
|
std::string directory;
|
|
while (std::getline(stream, directory, ':')) {
|
|
if (directory.empty()) {
|
|
directory = ".";
|
|
}
|
|
const std::string candidate = directory + "/" + name;
|
|
if (access(candidate.c_str(), X_OK) == 0) {
|
|
return candidate;
|
|
}
|
|
}
|
|
return {};
|
|
}
|
|
|
|
std::string trim(const std::string& value) {
|
|
const auto first = value.find_first_not_of(" \t\r\n");
|
|
if (first == std::string::npos) {
|
|
return {};
|
|
}
|
|
const auto last = value.find_last_not_of(" \t\r\n");
|
|
return value.substr(first, last - first + 1);
|
|
}
|
|
|
|
std::vector<std::string> splitLines(const std::string& text) {
|
|
std::vector<std::string> lines;
|
|
std::istringstream stream(text);
|
|
std::string line;
|
|
while (std::getline(stream, line)) {
|
|
line = trim(line);
|
|
if (!line.empty()) {
|
|
lines.push_back(line);
|
|
}
|
|
}
|
|
return lines;
|
|
}
|
|
|
|
} // namespace fws
|