00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040 #include "mmstools/mmsprocessmonitor.h"
00041 #include "mmstools/tools.h"
00042 #include <errno.h>
00043 #include <sys/types.h>
00044 #include <sys/wait.h>
00045 #include <signal.h>
00046 #include <stdlib.h>
00047
00048 MMSProcessMonitor::MMSProcessMonitor(unsigned int interval) : monitoringInterval(interval) {
00049 this->shutdown = false;
00050 }
00051
00052 MMSProcessMonitor::~MMSProcessMonitor() {
00053
00054 }
00055
00056 void MMSProcessMonitor::commenceShutdown() {
00057 DEBUGMSG("PROCESSMONITOR", "Processmonitor shutdown initiated.");
00058 this->shutdown = true;
00059 }
00060
00061 void MMSProcessMonitor::addProcess(std::string process) {
00062 MMSPROCESS_TASK task;
00063 task.cmdline = process;
00064 processes.push_back(task);
00065 }
00066
00067 void MMSProcessMonitor::addProcess(const char *process) {
00068 MMSPROCESS_TASK task;
00069 task.cmdline = process;
00070 processes.push_back(task);
00071 }
00072
00073 bool MMSProcessMonitor::startprocess(MMSPROCESS_TASKLIST::iterator &it) {
00074 pid_t pid = fork();
00075
00076 if(pid == -1) {
00077 return false;
00078 }
00079 if(pid == 0) {
00080 char *argv[255];
00081 argv[0]=(char *)it->cmdline.c_str();
00082 argv[1]=NULL;
00083 DEBUGMSG("PROCESSMONITOR", "Starting process %s", it->cmdline.c_str());
00084 execv(it->cmdline.c_str(),argv);
00085 DEBUGMSG("PROCESSMONITOR", "Starting of process %s failed. (ERRNO: %d)", it->cmdline.c_str(), errno);
00086 exit(1);
00087 }
00088
00089 it->pid=pid;
00090 return true;
00091 }
00092
00093 bool MMSProcessMonitor::checkprocess(MMSPROCESS_TASKLIST::iterator &it) {
00094 if(kill(it->pid,0)==0)
00095 return true;
00096 else
00097 return false;
00098
00099 }
00100 bool MMSProcessMonitor::killprocess(MMSPROCESS_TASKLIST::iterator &it) {
00101 DEBUGMSG("PROCESSMONITOR", "Killing process %s (%d)", it->cmdline.c_str(), it->pid);
00102 if(kill(it->pid,SIGTERM)==0)
00103 return true;
00104 else
00105 return false;
00106
00107 }
00108
00109 void MMSProcessMonitor::threadMain() {
00110 for(MMSPROCESS_TASKLIST::iterator it = this->processes.begin();it != this->processes.end();it++) {
00111 startprocess(it);
00112 }
00113
00114 while(1) {
00115 if(shutdown) {
00116 for(MMSPROCESS_TASKLIST::iterator it = this->processes.begin();it != this->processes.end();it++) {
00117 killprocess(it);
00118 }
00119 return;
00120 }
00121
00122 for(MMSPROCESS_TASKLIST::iterator it = this->processes.begin();it != this->processes.end();it++) {
00123 if(!checkprocess(it)) {
00124 startprocess(it);
00125 }
00126 }
00127 int status;
00128 while(waitpid(-1, &status, WNOHANG)>0);
00129 sleep(this->monitoringInterval);
00130 }
00131
00132 }
00133