/* * rename-log.c - check the size of a given log file in the '/tmp/var/log' * directory. If it is larger then 1024KB, rename it to * a have a '.old' suffix and create a new, empty log file. * * IMPORTANT NOTE: we intentionally use a fictitious log directory. Do NOT * use this program against your system's real log directory. */ #include /* standard input/output routines. */ #include /* access(), etc. */ #include /* stat(), etc. */ #include /* open(), close(), etc. */ #include /* malloc(), etc. */ #include /* strcpy(), strcat(). */ #define LOG_DIR "/tmp/var/log" /* full path to the logs directory. */ #define FILE_SIZE 1024*1024 /* size of file to rename - 1024KB. */ #define FILE_SUFFIX ".old" /* suffix for old log file. */ /* * function: main. * input: name of a log file. * output: log file is being renamed if it is too big. */ void main(int argc, char* argv[]) { char* file_name; /* name of the log file. */ char* new_file_name; /* new name for the log file. */ struct stat file_status; /* status info of the log file. */ int fd; /* descriptor for new file. */ mode_t file_mode; /* permissions of old log file. */ /* read command line arguments */ if (argc != 2 || !argv[1]) { fprintf(stderr, "Usage: %s \n", argv[0]); exit(1); } file_name = argv[1]; new_file_name = (char*)malloc(strlen(file_name)+strlen(FILE_SUFFIX)+1); if (!new_file_name) { fprintf(stderr, "Out of memory\n"); exit(1); } strcpy(new_file_name, file_name); strcat(new_file_name, FILE_SUFFIX); /* check we have read/write permissions to the /tmp/var/log directory. */ if (access(LOG_DIR, F_OK) == -1) { fprintf(stderr, "Directory '%s' does not exist.\n", LOG_DIR); exit(1); } if (access(LOG_DIR, R_OK | W_OK) == -1) { fprintf(stderr, "Directory '%s': access denied.\n", LOG_DIR); exit(1); } /* switch current directory to the logs directory. */ if (chdir(LOG_DIR) == -1) { fprintf(stderr, "Cannot change directory to '%s':", LOG_DIR); perror(""); exit(1); } /* check the size of the file. */ if (stat(file_name, &file_status) == -1) { fprintf(stderr, "Cannot stat file '%s':", file_name); perror(""); exit(1); } if (file_status.st_size > FILE_SIZE) { if (rename(file_name, new_file_name) == -1) { fprintf(stderr, "Cannot rename '%s' to '%s':", file_name, new_file_name); perror(""); exit(1); } /* create a new, empty log file, with the same access permissions */ /* as the original log file had. */ file_mode = file_status.st_mode & ~S_IFMT; umask(0); fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, file_mode); if (fd < 0) { fprintf(stderr, "Failed creating empty log file:"); perror(""); exit(1); } close(fd); } }