Logo Search packages:      
Sourcecode: mswatch version File versions  Download package

util.cc

#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <sstream>
#include <string>

#include "compat.h"
#include "util.h"

using std::stringstream;
using std::string;

int set_signal_handler(int sig, void (*handler)(int))
{
      struct sigaction sa;
      struct sigaction prev_sa;

      memset(&sa, 0, sizeof(sa));
      sa.sa_handler = handler;
      sigemptyset(&sa.sa_mask);
      sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;

      if (TEMP_FAILURE_RETRY(sigaction(sig, NULL, &prev_sa)) == -1)
      {
            perror("sigaction");
            return -1;
      }
      if (prev_sa.sa_handler == SIG_DFL && TEMP_FAILURE_RETRY(sigaction(sig, &sa, NULL)) == -1)
      {
            perror("Cannot set signal handler");
            return -1;
      }
      return 0;
}

void error(const char* format, ...)
{
      const char* errstr = strerror(errno);
      va_list val;
      va_start(val, format);
      vfprintf(stderr, format, val);
      if (strchr(format, '\n') == NULL)
            fprintf(stderr, ": %s\n", errstr);
      va_end(val);
}

void die_if(int cond, const char* format, ...)
{
      const char* errstr;
      va_list val;

      if (!cond)
            return;

      va_start(val, format);
      errstr = strerror(errno);
      vfprintf(stderr, format, val);
      if (strchr(format, '\n') == NULL)
            fprintf(stderr, ": %s\n", errstr);
      exit(1);
}

string itos(int x)
{
      stringstream xs;
      xs << x;
      return xs.str();
}

char* itoa(int x)
{
      return strdup(itos(x).c_str());
}

void localtime_str(char* str, size_t str_len, const time_t* t)
{
      strftime(str, str_len, "%F %X", localtime(t));
}

void localtime_str_now(char* str, size_t str_len)
{
      time_t t = time(NULL);
      localtime_str(str, str_len, &t);
}

string mkfilename(const string& path1, const string& path2)
{
      if (path1.empty() && path2.empty())
            return "/";
      if (path2.empty())
            return path1;
      if (path1.empty())
            return path2;

      string sep;
      if (path1[path1.size() - 1] != '/')
            sep = "/";
            
      return path1 + sep + path2;
}

void drain_fd(int fd)
{
      int r;
      do {
            char c;
            r = TEMP_FAILURE_RETRY(read(fd, &c, 1));
      } while (r > 0);
      assert(r < 0 && errno == EAGAIN);
}

Generated by  Doxygen 1.6.0   Back to index