I have created two pipes for client and server using FIFO named pipes. Then I tried to execute the communication between client and server. The communication works when sending messages from client to server but not vice versa. kindly help.
here are the three codes :
fifo.c (to create the pipes)
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
main()
{
int file1,file2;
int fd;
char str[256];
char temp[4]="how";
char temp1[4];
file1 = mkfifo("fifo_server",0666);
if(file1<0) {
printf("Unable to create a fifo");
exit(-1);
}
file2 = mkfifo("fifo_client",0666);
if(file2<0) {
printf("Unable to create a fifo");
exit(-1);
}
printf("fifos server and child created successfuly\n ");
}
server.c (to send and receive from client)
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
main()
{
FILE *file1;
int fifo_server,fifo_client;
char *choice;
char *buf;
if(fork() == 0)
{
while(1)
{
fifo_server = open("fifo_server",O_RDWR);
if(fifo_server<1) {
printf("Error opening file");
}
read(fifo_server,choice,sizeof(choice));
printf("%s\n",choice);
close(fifo_server);
}
//sleep(3);
}
else
{
while(1)
{
buf = malloc(10*sizeof(char));
scanf("%s",buf);
fifo_client = open("fifo_client",O_RDWR);
if(fifo_client<1) {
printf("Error opening file");
}
write(fifo_client,buf,sizeof(buf));
close(fifo_client);
}
}
close(fifo_server);
close(fifo_client);
}
client.c (to send and receive from server)
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
main()
{
FILE *file1;
int fifo_server,fifo_client;
char str[256];
char *buf;
char *choice;
printf("Welcome to chat\n\n");
if(fork() == 0)
{
while(1)
{
choice = malloc(10*sizeof(char));
scanf("%s",choice);
fifo_server=open("fifo_server",O_RDWR);
if(fifo_server < 1) {
printf("Error in opening file");
exit(-1);
}
write(fifo_server,choice,sizeof(choice));
//sleep(10);
}
}
else{
while(1)
{
fifo_client = open("fifo_client",O_RDWR);
if(fifo_client<1) {
printf("Error opening file");
exit(1);
}
read(fifo_client,choice,sizeof(choice));
printf("%s\n",choice);
/*
fifo_client=open("fifo_client",O_RDWR);
if(fifo_client < 0) {
printf("Error in opening file");
exit(-1);
}
buf=malloc(10*sizeof(char));
read (fifo_client,buf,sizeof(buf));
printf("\n %s***\n",buf);
*/
}
}
close(fifo_server);
close(fifo_client);
}
Some observations:
choice
but you never allocate memory to it.buf[512]
for read()s from network and write()s as well (write() strnlen() bytes/chars).For example, instead of:
Do something like: