I try to wrap my head around FIFO and come up with a simple server and client program.
I am not trying to do something unusual, just to make one process that will act as a "server", this process will "listen" to any messages sent by another process; customer.
Here is what I wrote:
server.c
#include<stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define INGOING "clientToServer.fifo"
#define BUFFER 200
int main(int argc, char *argv[]) {
char in[BUFFER];
mkfifo(INGOING, 0666);
printf("Welcome to server.\n");
printf("channel for sending messages to server is %s\n", INGOING);
int in_fd=open(INGOING, O_RDONLY);
if (in_fd==-1) {
perror("open error");
exit(-1);
}
while (read(in_fd, in, BUFFER)>0) {
printf("You sent %s to server.\n", in);
}
return 2;
}
As you can see, this is pretty straight forward when I ran this in the background with a help ./server.out&that was blocked during a call readand expected someone to write to clientToServer.fifo. so far so good.
Now consider the end of the client:
client.c
#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#define BUFFER 200
int main(int argc, char *argv[]) {
char input[BUFFER]={0};
int out_fd=open("clientToServer.fifo", O_WRONLY);
if (out_fd==-1) {
perror("open error");
}
while (1) {
printf("What would you like to send to server? (send Quit to quit)\n");
fgets(input, BUFFER, stdin);
if (input[strlen(input)-1]=='\n') {
input[strlen(input)-1]='\0';
}
if (strcmp(input, "Quit")==0) {
printf("Bye!");
break;
}
if (write(out_fd, input, strlen(input))==-1) {
perror("write error");
}
}
return 1;
}
. . ./a.out , - , server.out You sent %s to server.
, Quit , a.out , while server.out . read server.out , .
? read server.out , a.out?