0

I have two C files fifoserver.c and fifoclient.c

The server program creates a FIFO for reading and displays anything it receives from the named pipe to the standard output. The client program, on the other hand, is supposed to open the FIFO created by the server program for writing, and writes anything that it reads from the standard input to the named pipe.

However, my fifoclient.c program is unable to read any user input and prints out no input. Why?
Here's my code:

fifoserver.c

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

#define FIFONAME "myfifo"

int main(void){

    int n,fd;
    char buffer[1024];
    unlink(FIFONAME);

    //create FIFO

    if(mkfifo(FIFONAME,0666)<0){
        perror("server: mkfifo");
        exit(1);
    }
    //open FIFO for reading
    if((fd = open(FIFONAME, O_RDONLY))<0){
        perror("server: open");
        exit(1);
    }
    //READ from fifo UNTIL end of tile and print 
    //what we get on the standard input
    while((n=read(fd,buffer,sizeof(buffer)))>0){
        write(1, buffer, sizeof(buffer));
    }

    close(fd);
    exit(0);
}

fifoclient.c

//fifoclient.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define FIFONAME "myfifo"

int main(void){

    int n,fd;
    char buffer[1024];

    /* open, read, and display the message from the FIFO */
    if((fd = open(FIFONAME, O_WRONLY))<0){
        perror("client: open");
        exit(1);
    }
    //read from standard input and copy data to the FIFO
    while((n=read(fd,buffer,sizeof(buffer)))>0){
        fgets(buffer, sizeof(buffer), stdin);
        write(fd, buffer, strlen(buffer)+1);
    }


    close(fd);
    exit(0);
}

To execute these two programs, run the server program in the background before running the client program. For example:

./fifoserver &
./fifoclient < /etc/passwd

Here's my output when I execute the programs:
output

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
fredjohnson
  • 187
  • 2
  • 10
  • 18
  • 1
    Isn't the client supposed to read its standard input (`/etc/passwd` via redirection) and write that to the FIFO? You have it trying to read from the FIFO which was opened for write only, so of course it fails and exits the loop. Maybe you had in mind to use `STDIN_FILENO` instead of `fd` in the `read()` call? Or, better, use `while (fgets(buffer, sizoef(buffer), stdin) != 0)` instead of using `read()` at all. – Jonathan Leffler Oct 15 '17 at 03:20
  • @JonathanLeffler Thank you! I think I was able to get the right output: [output pics](https://imgur.com/a/Y1GJS) – fredjohnson Oct 15 '17 at 03:52

0 Answers0