Add contrib.
[doldaconnect.git] / config / speedrec.c
CommitLineData
d3372da9 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>
d3372da9 9#include <signal.h>
10
e374cdc3 11char buf[65536];
d3372da9 12volatile int eof;
13
14void sighandler(int sig)
15{
16 eof = 1;
17}
18
19int 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;
d3372da9 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 {
e374cdc3 44 ret = read(0, buf, sizeof(buf));
d3372da9 45 if((ret < 0) && (errno != EINTR))
46 {
e374cdc3 47 perror("cannot read");
d3372da9 48 exit(1);
49 }
e374cdc3 50 if((ret == 0) || eof)
51 break;
0346bf95 52 if(starttime == 0)
53 starttime = time(NULL);
54 endtime = time(NULL);
e374cdc3 55 datalen = ret;
56 numbytes += ret;
57 while(datalen > 0)
d3372da9 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 }
d3372da9 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}