00001 #include <sys/select.h>
00002 #include <time.h>
00003 #include <unistd.h>
00004 #include <sys/types.h>
00005 #include <sys/wait.h>
00006 #include <stdio.h>
00007 #include <stdlib.h>
00008 #include <string.h>
00009 #include <syslog.h>
00010 #include <errno.h>
00011
00012 #include "../include/monitor.h"
00013
00014
00015 extern int verbose;
00016
00017 void logRotate(FILE ** handle, char * path, char * pattern) {
00018 static char logName[1024] = "";
00019
00020 char strftimeName[128] = "";
00021 char newLogName[1024] = "";
00022
00023 time_t t;
00024 struct tm *tmp;
00025
00026 t = time(NULL);
00027 tmp = localtime(&t);
00028 if (tmp == NULL) {
00029 syslogMonitor(LOG_ERR, MON_INFO, "logrotate.localtime",
00030 "can't get localtime for new logname. continue with old one");
00031 return;
00032 }
00033
00034 if (strftime(strftimeName, sizeof(strftimeName)-1, pattern, tmp) == 0) {
00035 syslogMonitor(LOG_ERR, MON_INFO, "logrotate.strftime",
00036 "strftime returned 0 for new logname. continue with old one");
00037 return;
00038 }
00039
00040 snprintf(newLogName, sizeof(newLogName)-1, "%s/%s", path, strftimeName);
00041
00042 if (0 != strncmp(logName, newLogName, sizeof(logName)-1)) {
00043 if (0 != verbose) {
00044 syslog(LOG_INFO, "actual logfile name: %s", logName);
00045 syslog(LOG_INFO, "new logfile name: %s", newLogName);
00046 }
00047
00048 if (NULL != *handle) {
00049 fclose(*handle);
00050
00051 pid_t gzipPid = fork();
00052
00053 switch(gzipPid) {
00054 pid_t tmpPid;
00055
00056 case 0:
00057
00058
00059 tmpPid = fork();
00060 if (0 == tmpPid) {
00061 syslog(LOG_INFO, "gzip: %s", logName);
00062 if (-1 == execl("/bin/gzip", "/bin/gzip", "-9", logName, (char *) 0)) {
00063 syslogMonitor(LOG_ERR, MON_INFO, "logrotate.gzip",
00064 "execl failed for gzip %s: %s", logName, strerror(errno));
00065 }
00066 }
00067 exit(EXIT_SUCCESS);
00068
00069 case -1:
00070 syslogMonitor(LOG_ERR, MON_INFO, "logrotate.fork",
00071 "fork failed for gzip %s: %s", logName, strerror(errno));
00072 break;
00073
00074 default:
00075 wait(NULL);
00076 break;
00077 }
00078 }
00079
00080 strncpy(logName, newLogName, sizeof(logName)-1);
00081 *handle = fopen(logName, "w");
00082 }
00083 }