#include #include #include /** viewnews.c - read the news file with read locking **/ /** usage: viewnews reportname **/ #define oops(m,x) { perror(m); exit(x); } main(int ac, char *av[]) { int fd_report, nread; char buf[BUFSIZ]; if ( ac != 2 ){ fprintf(stderr,"usage: viewnews report\n"); exit(1); } if ( (fd_report = open(av[1],O_RDONLY)) == -1 ) oops(av[2],3); lock_operation(fd_report, F_RDLCK); while( (nread = read(fd_report, buf, BUFSIZ)) > 0 ) write(1, buf, nread ); lock_operation(fd_report, F_UNLCK); close(fd_report); } 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); }