Having problem with chat client server.. I dont know why server is not sending the message to multiple client

//client.cpp

#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>

//krunal m patel
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);
}


// server.cpp //krunal m patel


#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

int main()
{
int client_to_server;
char *myfifo = "/tmp/client_to_server_fifo";

int server_to_client;
char *myfifo2 = "/tmp/server_to_client_fifo";

char buf[BUFSIZ];

/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
mkfifo(myfifo2, 0666);

/* open, read, and display the message from the FIFO */
client_to_server = open(myfifo, O_RDONLY);
server_to_client = open(myfifo2, O_WRONLY);

printf("Server ON.\n");

while (1)
{
read(client_to_server, buf, BUFSIZ);

if (strcmp("exit",buf)==0)
{
printf("Server OFF.\n");
break;
}

else if (strcmp("",buf)!=0)
{
printf("Received: %s\n", buf);
printf("Sending back...\n");
write(server_to_client,buf,BUFSIZ);
}

/* clean buf from any data */
memset(buf, 0, sizeof(buf));
}

close(client_to_server);
close(server_to_client);

unlink(myfifo);
unlink(myfifo2);
return 0;
}
Please format your code using the format tags. It's impossible to read otherwise.

You cannot use a FIFO as your IPC mechanism if you expect to connect to multple processes. A FIFO is kind of like a pipe, one end connects to one process and the other end connects to another process, and that's it. You can't support multiple concurrent connections with a single pipe.

Also, forget malloc and char*. You need buffers, so create fixed length strings as in: char choice[32];
Last edited on
Registered users can post here. Sign in or register to post.