#include #include #include /** publishnews.c - read items from a FIFO publish to a file **/ /** usage: publishnews fifoname reportname **/ /** note: uses an array of arrays and copies them down **/ /** Need to change to a circular list **/ #define LINES 10 #define LINELEN 512 #define oops(m,x) { perror(m); exit(x); } char report[LINES][LINELEN]; main(int ac, char *av[]) { FILE *fp_report, *fp_fifo; int fd_report; int line; if ( ac != 3 ){ fprintf(stderr,"usage: publishnews fifo output\n"); exit(1); } if ((fp_fifo = fopen(av[1], "r")) == NULL ) oops(av[1],2); if ( (fd_report = open(av[2],O_CREAT|O_TRUNC|O_RDWR,0644)) == -1 ) oops(av[2],3); while( 1 ){ /** read next line from fifo */ if ( fgets(report[0],LINELEN,fp_fifo) == NULL ){ fclose(fp_fifo); fp_fifo = fopen(av[1],"r"); continue; } /** update report */ lock_operation(fd_report, F_WRLCK); fp_report = fopen(av[2],"w"); if ( fp_report == NULL ) oops(av[2],4); for(line = 0 ; line 0 ; line-- ) /* push down */ strcpy(report[line], report[line-1]); } } lock_operation(int fd, int op) { struct flock lock; lock.l_whence = SEEK_SET; lock.l_start = lock.l_len = 0; lock.l_pid = getpid(); lock.l_type = op; if ( fcntl(fd, F_SETLKW, &lock) == -1 ) oops("lock operation", 6); }