I'm practicing linux fifo reading and writing. I created two files. One is client.c, and another is server.c. I'm trying to swap the name of the two program. So I created two fifo. client first writes in AToB fifo, pending server to read. And then client waits for the server to write in BToA fifo.
Why both of the program didn't proceed to the end, and it seems both of them are waiting each other?
My result is as follows:
client.c
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char** argv)
{
char name[80];
char temp[80];
strcpy(name,"Harris");
name[strlen(name)]='\0';
printf("Original name: %s\n",name);
char * myfifo = "AToB";
char * myfifo2 = "BToA";
mkfifo(myfifo, 0666);
mkfifo(myfifo2, 0666);
/////////////////////////////////////////////
int fd = open(myfifo, O_WRONLY);
int fd2 = open(myfifo2, O_RDONLY);
//////////////////////////////////////
write(fd, name, strlen(name)+1);
close(fd);
read(fd2, temp, sizeof(temp));
close(fd2);
strcpy(name,temp);
name[strlen(name)]='\0';
printf("After name: %s\n",name);
return 0;
}
server.c
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char** argv)
{
char name[80];
char temp[80];
strcpy(name,"Amy");
printf("Original name: %s\n",name);
char * myfifo = "AToB";
char * myfifo2 = "BToA";
int fd = open(myfifo2, O_WRONLY);
int fd2 = open(myfifo, O_RDONLY);
////////////////////////////////////////
read(fd2, temp, sizeof(temp));
close(fd2);
write(fd, name, strlen(name)+1);
close(fd);
strcpy(name,temp);
name[strlen(name)]='\0';
printf("After name: %s\n",name);
return 0;
}
Updated: I fixed the problem myself. It seems that I cannot open multiple fifo at once. If I modify the code like the following, it will work.
int fd = open(myfifo, O_WRONLY);
write(fd, name, strlen(name)+1);
close(fd);
int fd2 = open(myfifo2, O_RDONLY);
read(fd2, temp, sizeof(temp));
close(fd2);

Updated: I fixed the problem myself. It seems that I cannot open multiple fifo at once. If I modify the code like the following, it will work.