/* a sample program that the parent reads what its child
has written to a named pipe. */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define BUFSIZE 256

int main() {
    mode_t fifo_mode = S_IRUSR | S_IWUSR;
    int fd;
    int status;
    char buf[BUFSIZE];
    unsigned strsize;
    int mychild;
    char *name;

    if((name = tmpnam(NULL)) == NULL) {
        printf("temp file name could not be made. \n");
        exit(1);
    }
    if((mkfifo(name,fifo_mode) == -1) && (errno != EEXIST)) {
        fprintf(stdout,"Could not create a named pipe: temp\n");
        exit(1);
    }
    if((mychild = fork()) == -1) {
        perror("Could not fork");
        exit(1);
    }
    else if(mychild == 0) {
        fprintf(stdout, "Child[%ld] about to open FIFO temp\n",
             (long) getpid());
        if((fd = open(name,O_WRONLY|O_CREAT)) == -1) {
            perror("Child cannot open FIFO");
            exit(1);
        }
        sprintf(buf,"This was written by the child[%ld]\n",(long) getpid());
        strsize = strlen(buf)+1;
        if(write(fd,buf,strsize) != strsize) {
            fprintf(stdout,"Child write to FIFO failed\n");
            exit(1);
        }
        fprintf(stdout, "Child[%ld] is done\n", (long) getpid());
    }
    else {
        fprintf(stdout,"Parent[%ld] about to open FIFO temp\n",
                (long)getpid());
        if((fd = open(name,O_RDONLY | O_NONBLOCK | O_CREAT)) == -1) {
            perror("Parent cannot open FIFO");
            exit(1);
        }
        fprintf(stdout,"Parent[%ld] about to read\n",(long) getpid());
        while ((wait(&status) == -1) && (errno == EINTR)) ;
             if(read(fd,buf,BUFSIZE)<=0) {
            perror("Parent read from FIFO failed \n");
            exit(1);
        }
        fprintf(stdout,"Parent[%ld] got: %s\n",(long)getpid(),buf);
    }
}
