#include "main.h" #include "conf.h" #include "libconf.h" conf *conf_head = NULL; int get_process_pid(char *proces_name) { char bufer[PATH_SIZE]; char comm[PATH_SIZE]; char proc_comm_name[PATH_SIZE]; int num[PATH_SIZE] = { 0 }; int n = 0; FILE *fp; DIR *dir; struct dirent *ptr; dir = opendir("/proc"); while ((ptr = readdir(dir)) != NULL) { if (ptr->d_type == 4 && strcasecmp(ptr->d_name, ".") && strcasecmp(ptr->d_name, "..")) { bzero(bufer, 0); sprintf(comm, "/proc/%s/comm", ptr->d_name); if (access(comm, F_OK) == 0) { fp = fopen(comm, "r"); if (fgets(bufer, PATH_SIZE - 1, fp) == NULL) { fclose(fp); continue; } sscanf(bufer, "%s", proc_comm_name); if (!strcmp(proces_name, proc_comm_name)) { num[n] = atoi(ptr->d_name); n += 1; } fclose(fp); } } } n -= 1; // 去除最后一个搜索时的本身进程 closedir(dir); if (num[0] > 0) return num[0]; else return 0; } char *times() { time_t t; struct tm *timeinfo; time(&t); timeinfo = localtime(&t); return asctime(timeinfo); } int logs(char *str, char *configfile) { FILE *fp = NULL; fp = fopen(read_conf(configfile, "global", "LOGFILE"), "a+"); fprintf(fp, str); return fclose(fp); } int8_t copy_new_mem(char *src, int src_len, char **dest) { *dest = (char *)malloc(src_len + 1); if (*dest == NULL) return 1; memcpy(*dest, src, src_len); *((*dest)+src_len) = '\0'; return 0; } int loop(char *configfile, conf *p) { conf *conf = p; FILE *fp; char buffer[CACHE_SIZE]; char log_content[CACHE_SIZE]; memset(log_content, 0, CACHE_SIZE); while (1) { while (conf) { if (conf->PROCESS) { if (get_process_pid(conf->PROCESS_name) <= 0) { strcpy(log_content, times()); strcat(log_content, conf->PROCESS_name); strcat(log_content, " Not running\n"); logs(log_content, configfile); fp = _popen(conf->PROCESS_command, "r"); memset(buffer, 0, CACHE_SIZE); while (fgets(buffer, sizeof(buffer), fp)) { //printf("%s", buffer); logs(buffer, configfile); } _pclose(fp); } else { strcpy(log_content, times()); strcat(log_content, conf->PROCESS_name); strcat(log_content, " Running\n"); logs(log_content, configfile); } } conf = conf->next; } conf = p; sleep(atoi(read_conf(configfile, "global", "TIME"))); } return 0; } int main(int argc, char *argv[], char **env) { char configfile[PATH_SIZE]; int opt; memset(configfile, 0, PATH_SIZE); while ((opt = getopt(argc, argv, "c:h?")) != -1) { switch (opt) { case 'c': strcpy(configfile, optarg); break; case 'h': case '?': printf("%s\n", "Process daemon\n"\ "Author: AIXIAO@AIXIAO.ME\n"\ "Usage: [-?h] [-c filename]\n"\ "\n"\ "Options:\n"\ "-c : set configuration file, (default: daemon.conf)\n"\ "-? -h : help information\n"); exit(1); break; default: break; } } if (strlen(configfile) == 0) { strcpy(configfile, "daemon.conf"); } if (daemon(1, 1)) { // 守护, 脱离终端 perror("daemon"); } read_conf_link(configfile); /* Test Code print_conf(conf_head); free_conf(conf_head); exit(0); */ loop(configfile, conf_head); free_conf(conf_head); return 0; }