1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
/* http://delahaye.emmanuel.free.fr/clib/ */
#include "psleep/inc/psleep.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define F_LOG "log.txt"
#define F_INDEX "index.txt"
void *trace (void *context)
{
FILE *fp = fopen (F_LOG, "a");
if (fp != NULL)
{
int i;
for (i = 0; i < 10; i++)
{
char sdate[] = "xxxx/xx/xx xx:xx:xx";
time_t t = time (NULL);
struct tm tm = *localtime (&t);
strftime (sdate, sizeof sdate, "%Y/%m/%d %H:%M:%S", &tm);
fprintf (fp, "%s\n", sdate);
{
int sec = 1 + rand () % 3;
msleep (1000 * sec);
}
}
fclose (fp), fp = NULL;
}
printf ("trace_end\n");
(void) context;
return NULL;
}
void *analyse (void *context)
{
long ndx = 0;
/* get the current index */
{
FILE *fp = fopen (F_INDEX, "r");
if (fp != NULL)
{
char ligne[32];
fgets (ligne, sizeof ligne, fp);
ndx = strtol (ligne, NULL, 10);
fclose (fp), fp = NULL;
}
}
printf ("ndx=%ld\n", ndx);
/* read the log file every 10 seconds */
{
int i;
for (i = 0; i < 4; i++)
{
FILE *fp = fopen (F_LOG, "r");
if (fp != NULL)
{
char line[32];
/* skip the beginnig of the file */
long j = 0;
while (fgets (line, sizeof line, fp) != NULL && j < ndx)
{
j++;
}
/* display the end of the file */
while (fgets (line, sizeof line, fp) != NULL)
{
puts (line);
j++;
}
fclose (fp), fp = NULL;
/* record the last read position */
{
FILE *fp = fopen (F_INDEX, "w");
if (fp != NULL)
{
fprintf (fp, "%ld\n", j);
fclose (fp), fp = NULL;
}
}
}
msleep (10 * 1000);
}
}
printf ("analyse_end\n");
(void) context;
return NULL;
}
int main (void)
{
pthread_t th_trace;
pthread_t th_analyse;
srand (time (NULL));
pthread_create (&th_trace, NULL, trace, NULL);
pthread_create (&th_analyse, NULL, analyse, NULL);
pthread_join (th_trace, NULL);
pthread_join (th_analyse, NULL);
printf ("end\n");
return 0;
} |