Skip to content

Instantly share code, notes, and snippets.

@jmlvanre
Created September 23, 2015 23:32
Show Gist options
  • Save jmlvanre/99d23017abfe9caab6d5 to your computer and use it in GitHub Desktop.
Save jmlvanre/99d23017abfe9caab6d5 to your computer and use it in GitHub Desktop.
systemd-verify
// clang++-3.6 -std=c++11 verify.cc -overify-systemd; ./verify-systemd
#include <sstream>
#include <stdexcept>
#include <string>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
namespace os {
// Success, result
inline std::string realpath(const std::string& path)
{
char temp[4096];
if (::realpath(path.c_str(), temp) == NULL) {
if (errno == ENOENT || errno == ENOTDIR) {
throw std::runtime_error("no real path");
}
throw std::runtime_error("realpath error");
}
return std::string(temp);
}
// Success, result
std::pair<bool, std::string> shell(const std::string& command)
{
FILE* file;
std::ostringstream stdout;
if ((file = popen(command.c_str(), "r")) == NULL) {
return std::make_pair(false, "Failed to run command");
}
char line[1024];
while (fgets(line, sizeof(line), file) != NULL) {
stdout << line;
}
if (ferror(file) != 0) {
pclose(file); // Ignoring result since we already have an error.
return std::make_pair(false, "Error reading output of command");
}
int status;
if ((status = pclose(file)) == -1) {
return std::make_pair(false, "Failed to get status");
}
if (WIFSIGNALED(status)) {
return std::make_pair(false, "Running command was interrupted");
} else if ((WEXITSTATUS(status) != EXIT_SUCCESS)) {
return std::make_pair(false, "Failed to run command");
}
return std::make_pair(true, stdout.str());
}
}
int main(int argc, char** argv) {
bool is_systemd = false;
printf("Verifying systemd Init check:\n");
std::string path = os::realpath("/sbin/init");
printf("Real path of [/sbin/init] = [%s]\n", path.c_str());
std::string command = path + " --version";
std::pair<bool, std::string> result = os::shell(command);
if (result.first) {
printf("Result of executing [%s] = [%s]\n", command.c_str(), result.second.c_str());
std::istringstream versionString(result.second);
std::string name;
int version;
versionString >> name >> version;
if (!versionString.good()) {
printf("Failed to parse systemd version from [%s]\n", result.second.c_str());
is_systemd = false;
} else if (name == "systemd") {
is_systemd = true;
printf("Detected systemd version [%d]\n", version);
}
} else {
printf("Executing [%s] failed: [%s]\n", command.c_str(), result.second.c_str());
}
if (is_systemd) {
printf("\n===============================\nThis system WILL be treated as running on systemd\n===============================\n");
} else {
printf("===============================\nThis system FAILED to detect systemd\n===============================\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment