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