| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303 | // \file service.cpp
//
// Copyright (C) 2014 MicroNeil Research Corporation.
//
// This program is part of the MicroNeil Research Open Library Project. For
// more information go to http://www.microneil.com/OpenLibrary/index.html
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 59 Temple
// Place, Suite 330, Boston, MA 02111-1307 USA
//==============================================================================
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <thread>
#include <chrono>
#include "service.hpp"
// Main program for *nix daemon.
int main(int argc, char *argv[]) {
  CodeDweller::Service &service = CodeDweller::Service::getInstance();
  return service.main(argc, argv);
}
namespace CodeDweller {
  std::mutex Service::objectMutex;
  Service::Service() :
    pauseReceived(false),
    resumeReceived(false),
    restartReceived(false),
    stopReceived(false) {
  }
  Service &Service::getInstance() {
    std::lock_guard<std::mutex> scopeMutex(objectMutex);
    static Service service;
    return service;
  }
  int Service::main(int argc, char *argv[]) {
    // Load the arguments.
    loadArguments(argc, argv);
    pid_t pid;
    // Fork the process.
    pid = fork();
    if (pid < 0) {
      perror("Error from first fork");
      return(EXIT_FAILURE);
    }
    // Terminate the parent.
    if (pid > 0) {
      return(EXIT_SUCCESS);
    }
    // This is the child.  Become the session leader.
    if (setsid() < 0) {
      perror("Error from setsid");
      return(EXIT_FAILURE);
    }
    // Fork again.
    pid = fork();
    if (pid < 0) {
      perror("Error from second fork");
      return(EXIT_FAILURE);
    }
    // Terminate the parent.
    if (pid > 0) {
      return(EXIT_SUCCESS);
    }
    // Set default file permissions.  This call always succeeds.
    umask(0);
    // Disassociate the process from the default directory of the
    // grandparent.
    if (chdir("/") != 0) {
      perror("Error from chdir");
      return(EXIT_FAILURE);
    }
    // Initialize the set of signals to wait for.
    if (sigemptyset(&signalSet) != 0) {
      perror("Error from sigemptyset");
      return(EXIT_FAILURE);
    }
    if ((sigaddset(&signalSet, SIGTSTP) != 0) ||
	(sigaddset(&signalSet, SIGCONT) != 0) ||
	(sigaddset(&signalSet, SIGHUP) != 0) ||
	(sigaddset(&signalSet, SIGTERM) != 0)) {
      perror("Error from sigaddset");
      return(EXIT_FAILURE);
    }
    // Block the signals.
    if (sigprocmask(SIG_BLOCK, &signalSet, NULL) != 0) {
      perror("Error from sigprocmask");
      return(EXIT_FAILURE);
    }
    // Close all open file descriptors.
    for (int fd = 2; fd >= 0; fd--) {
      if (close(fd) != 0) {
	// There is no controlling terminal to send any message to.
	return(EXIT_FAILURE);
      }
    }
    // Connect standard I/O to the null device.
    int fd;
    // stdin.
    fd = open("/dev/null", O_RDONLY);
    if (fd < 0) {
      return(EXIT_FAILURE);
    }
    // stdout.
    fd = open("/dev/null", O_WRONLY);
    if (fd < 0) {
      return(EXIT_FAILURE);
    }
    // stderr.
    fd = open("/dev/null", O_WRONLY);
    if (fd < 0) {
      return(EXIT_FAILURE);
    }
    // Start the thread to process messages.
    std::thread messageThread(&Service::processMessages, this);
    // Run the service.
    int status;
    status = run();
    // Send a Stop message so that messageThread exits.
    pthread_kill(messageThread.native_handle(), SIGTERM);
    messageThread.join();
    return(status);
  }
  void Service::loadArguments(int argc, char *argv[]) {
    for (int i = 0; i < argc; i++) {
      cmdLineArgs.push_back(argv[i]);
    }
  }
  const std::vector<std::string> &Service::arguments() {
    return cmdLineArgs;
  }
  void Service::onPauseCall(Callback &pauseFunctor) {
    std::lock_guard<std::mutex> scopeMutex(objectMutex);
    pauseCallbacks.push_back(&pauseFunctor);
  }
  void Service::onResumeCall(Callback &resumeFunctor) {
    std::lock_guard<std::mutex> scopeMutex(objectMutex);
    resumeCallbacks.push_back(&resumeFunctor);
  }
  void Service::onRestartCall(Callback &restartFunctor) {
    std::lock_guard<std::mutex> scopeMutex(objectMutex);
    restartCallbacks.push_back(&restartFunctor);
  }
  void Service::onStopCall(Callback &stopFunctor) {
    std::lock_guard<std::mutex> scopeMutex(objectMutex);
    stopCallbacks.push_back(&stopFunctor);
  }
  bool Service::receivedPause() {
    return (pauseReceived);
  }
  bool Service::receivedResume() {
    return (resumeReceived);
  }
  bool Service::receivedRestart() {
    return (restartReceived);
  }
  bool Service::receivedStop() {
    return (stopReceived);
  }
  void Service::clearReceivedPause() {
    pauseReceived = false;
  }
  void Service::clearReceivedResume() {
    resumeReceived = false;
  }
  void Service::clearReceivedRestart() {
    restartReceived = false;
  }
  void Service::clearReceivedStop() {
    stopReceived = false;
  }
  void Service::processMessages() {
    int sigNum;
    int status;
    while (true) {
      // Wait for a signal.
      status = sigwait(&signalSet, &sigNum);
      if (0 != status) {
	perror("Error from sigwait");
	// TODO:  Implement recovery.
	;
      }
      // Process the message.
      switch (sigNum) {
      case SIGTSTP:
	pauseReceived = true;
	for (auto callback : pauseCallbacks) {
	  (*callback)();
	}
	break;
      case SIGCONT:
	resumeReceived = true;
	for (auto callback : resumeCallbacks) {
	  (*callback)();
	}
	break;
      case SIGHUP:
	restartReceived = true;
	for (auto callback : restartCallbacks) {
	  (*callback)();
	}
	break;
      case SIGTERM:
	stopReceived = true;
	for (auto callback : stopCallbacks) {
	  (*callback)();
	}
	// Exit.
	return;
	break;
      default:
	;
      } // switch.
    } // while.
  }
}
 |