Created
October 13, 2012 03:12
-
-
Save syshack/3883073 to your computer and use it in GitHub Desktop.
tailf sourcecode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <unistd.h> | |
| #include <malloc.h> | |
| #include <sys/stat.h> | |
| #include <signal.h> | |
| //#include "mongo.h" | |
| #define _(s) s | |
| static size_t filesize(const char *filename) | |
| { | |
| struct stat sb; | |
| if (!stat(filename, &sb)) return sb.st_size; | |
| return 0; | |
| } | |
| static void tailf(const char *filename, int lines) | |
| { | |
| char **buffer; | |
| int head = 0; | |
| int tail = 0; | |
| FILE *str; | |
| int i; | |
| if (!(str = fopen(filename, "r"))) { | |
| } | |
| buffer = malloc(lines * sizeof(*buffer)); | |
| for (i = 0; i < lines; i++) buffer[i] = malloc(BUFSIZ + 1); | |
| while (fgets(buffer[tail], BUFSIZ, str)) { | |
| if (++tail >= lines) { | |
| tail = 0; | |
| head = 1; | |
| } | |
| } | |
| if (head) { | |
| for (i = tail; i < lines; i++) fputs(buffer[i], stdout); | |
| for (i = 0; i < tail; i++) fputs(buffer[i], stdout); | |
| } else { | |
| for (i = head; i < tail; i++) fputs(buffer[i], stdout); | |
| } | |
| fflush(stdout); | |
| for (i = 0; i < lines; i++) free(buffer[i]); | |
| free(buffer); | |
| } | |
| void restart(int num) | |
| { | |
| } | |
| int main(int argc, char **argv) | |
| { | |
| char buffer[BUFSIZ]; | |
| size_t osize, nsize; | |
| FILE *str; | |
| const char *filename; | |
| int count; | |
| int signum =11; | |
| signal(signum, restart); | |
| if (argc != 2) { | |
| fprintf(stderr, _("Usage: tailf logfile\n")); | |
| } | |
| filename = argv[1]; | |
| tailf(filename, 1); | |
| for (osize = filesize(filename);;) { | |
| nsize = filesize(filename); | |
| if (nsize != osize) { | |
| if (!(str = fopen(filename, "r"))) { | |
| } | |
| if (!fseek(str, osize, SEEK_SET)) | |
| while ((count = fread(buffer, 1, sizeof(buffer), str)) > 0) | |
| buffer[count+1] = '\0'; | |
| printf(buffer,1,count); | |
| printf("####################################"); | |
| fclose(str); | |
| osize = nsize; | |
| } | |
| usleep(250000); /* 250mS */ | |
| } | |
| return 0; | |
| } | |
| ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment