| 1 | #include <string.h> |
| 2 | #include <stdio.h> |
| 3 | #include <stdlib.h> |
| 4 | #include <sys/file.h> |
| 5 | #include <unistd.h> |
| 6 | #include <fcntl.h> |
| 7 | #include <errno.h> |
| 8 | #include <time.h> |
| 9 | #include <signal.h> |
| 10 | |
| 11 | char buf[65536]; |
| 12 | volatile int eof; |
| 13 | |
| 14 | void sighandler(int sig) |
| 15 | { |
| 16 | eof = 1; |
| 17 | } |
| 18 | |
| 19 | int main(int argc, char **argv) |
| 20 | { |
| 21 | int i; |
| 22 | int ret, fd; |
| 23 | time_t starttime, endtime; |
| 24 | long long numbytes; |
| 25 | size_t datalen; |
| 26 | FILE *recfile; |
| 27 | int thisrec, numrecs, numuses, maxrec; |
| 28 | int recs[5]; |
| 29 | |
| 30 | if(argc < 2) |
| 31 | { |
| 32 | fprintf(stderr, "usage: speedrec recfile\n"); |
| 33 | exit(1); |
| 34 | } |
| 35 | numbytes = 0; |
| 36 | starttime = endtime = 0; |
| 37 | datalen = 0; |
| 38 | eof = 0; |
| 39 | signal(SIGHUP, sighandler); |
| 40 | signal(SIGINT, sighandler); |
| 41 | signal(SIGTERM, sighandler); |
| 42 | while(1) |
| 43 | { |
| 44 | ret = read(0, buf, sizeof(buf)); |
| 45 | if((ret < 0) && (errno != EINTR)) |
| 46 | { |
| 47 | perror("cannot read"); |
| 48 | exit(1); |
| 49 | } |
| 50 | if((ret == 0) || eof) |
| 51 | break; |
| 52 | if(starttime == 0) |
| 53 | starttime = time(NULL); |
| 54 | endtime = time(NULL); |
| 55 | datalen = ret; |
| 56 | numbytes += ret; |
| 57 | while(datalen > 0) |
| 58 | { |
| 59 | ret = write(1, buf, datalen); |
| 60 | if((ret < 0) && (errno != EINTR)) |
| 61 | { |
| 62 | perror("cannot write"); |
| 63 | exit(1); |
| 64 | } |
| 65 | memmove(buf, buf + ret, datalen -= ret); |
| 66 | } |
| 67 | } |
| 68 | if((starttime == 0) || (endtime == 0) || (endtime == starttime)) |
| 69 | exit(0); |
| 70 | if(numbytes == 0) |
| 71 | exit(0); |
| 72 | thisrec = (int)(numbytes / ((long long)(endtime - starttime))); |
| 73 | if((fd = open(argv[1], O_RDWR | O_CREAT, 0666)) < 0) |
| 74 | { |
| 75 | perror(argv[1]); |
| 76 | exit(1); |
| 77 | } |
| 78 | recfile = fdopen(fd, "r+"); |
| 79 | close(0); |
| 80 | close(1); |
| 81 | flock(fd, LOCK_EX); |
| 82 | if(fscanf(recfile, "%i\n", &numuses) < 1) |
| 83 | numuses = 0; |
| 84 | if(fscanf(recfile, "%i\n", &maxrec) < 1) |
| 85 | maxrec = 0; |
| 86 | if(fscanf(recfile, "%i\n", &numrecs) < 1) |
| 87 | numrecs = 0; |
| 88 | for(i = 0; i < numrecs; i++) |
| 89 | fscanf(recfile, "%i\n", &recs[i]); |
| 90 | if(numrecs == 5) |
| 91 | { |
| 92 | for(i = 0; i < 4; i++) |
| 93 | recs[i] = recs[i + 1]; |
| 94 | numrecs = 4; |
| 95 | } |
| 96 | recs[numrecs++] = thisrec; |
| 97 | rewind(recfile); |
| 98 | ftruncate(fd, 0); |
| 99 | fprintf(recfile, "%i\n", numuses + 1); |
| 100 | fprintf(recfile, "%i\n", (thisrec > maxrec)?thisrec:maxrec); |
| 101 | fprintf(recfile, "%i\n", numrecs); |
| 102 | for(i = 0; i < numrecs; i++) |
| 103 | fprintf(recfile, "%i\n", recs[i]); |
| 104 | flock(fd, LOCK_UN); |
| 105 | fclose(recfile); |
| 106 | return(0); |
| 107 | } |