#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>

int count, fd1;
fd_set readfds;
struct timeval readtimeout;

struct flock* file_lock(short type, short whence) {
    static struct flock ret;
    ret.l_type = type;
    ret.l_start = 0;
    ret.l_whence = whence;
    ret.l_len = 0;
    ret.l_pid = getpid();
    return &ret;
}
 
int readIt(int fd, off_t fSize) {
    char* fLine;
    int    n;

    fLine = (char *) malloc(fSize);
    
    printf("fSize is %d\n", fSize);
    if ((n = read(fd, fLine, fSize)) != fSize) {
	printf("expected to read %d bytes: read %d bytes\n", fSize, n);
	free(fLine);
	return 1;
    }

    printf("%s\n", fLine);
    free(fLine);
    return 0;
} 

int main(int argc, char** argv) {
    int n;
    char c;
    char* mybuf;
    struct stat stbuf;
    char* fname = *++argv;

    if (stat(fname, &stbuf) == 0) {
	fd1 = open(fname, O_RDWR);
	readIt(fd1, stbuf.st_size);
    } else {
        umask(0);
        mkfifo(fname, 0600);
    
        fd1 = open(fname, O_RDWR);
        if (fd1 == -1) {
	    printf("could not open\n");
	    exit(1);
        }

    /* now lock the file */
    fcntl(fd1, F_SETLKW, file_lock(F_WRLCK, SEEK_SET));

    /* get read ready */
	FD_ZERO(&readfds);
	FD_SET(fd1, &readfds);
	readtimeout.tv_sec = 60;
	readtimeout.tv_usec = 0;
	if (1 == select(1+fd1, &readfds, 0, 0, &readtimeout)) {
	    if (FD_ISSET(fd1, &readfds)) {
		fstat(fd1, &stbuf);
		readIt(fd1, stbuf.st_size);
	    } else {
		printf("read not ready\n");
	    }
	} else {
	    printf("select failed\n");
	}
   } 
    close(fd1);

    unlink(fname); 
}
