auxiliar.cpp 1.62 KB
//
// Created by Imanol on 28-may-16.
//

#include "auxiliar.h"

void timer_handler(int signum) {
  if(signum == SIGVTALRM) {
    std::cout << servicename << " CRITICAL - timeout occurred" << std::endl;
    exit(2);
  }
}

int str2int(const std::string& str) {
  int num;
  std::stringstream sstream;
  sstream << str;
  if(!(sstream >> num)) {
    throw ConversionException("Integer conversion error");
  }
  return num;
}

std::string int2str(const int x) {
    std::string str;
    std::stringstream sstream;
    sstream << x;
    sstream >> str;
    return str;
}

std::string double2str(const double x) {
    std::string str;
    std::stringstream sstream;
    sstream << x;
    sstream >> str;
    return str;
}

double str2double(const std::string& str) {
  double num;
  std::stringstream sstream;
  sstream << str;
  if(!(sstream >> num)) {
    throw ConversionException("Double conversion error");
  }
  return num;
}

bool starts_with(const std::string& value, const std::string& begin) {
  return value.rfind(begin,0) == 0;
}

bool ends_with(const std::string& value, const std::string& ending) {
  if(ending.size() > value.size()) return false;
  return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}

int exec(const std::string& cmd, std::string& output) {
  output = "";
  FILE* pipe = popen(cmd.c_str(), "r");
  if(!pipe) {
    std::cout << "Error opening child process" << std::endl;
    exit(3);
  }
  char buffer[128];
  while(!feof(pipe)) {
    if(fgets(buffer, 128, pipe) != NULL) {
      output += buffer;
    }
  }
  return pclose(pipe)/256;
}