Hi all,
I am trying to create an application that uses TCP sockets under Unix, where multiple clients connect to one server. Each message sent by one client is forwarded to all other clients. I am using on the server side an array of int's declared at the beginning of the application, that will contain the socket descriptor returned by the "accept" function for each client that connects. After this, I am fork-ing a new child that will handle that client. All child processes need to access the array of int's in order to send to everyone the client messages.
My problem is that for the first client (child process), the array of int's has only one element, namely its own socket (file) descriptor, for the second client, the array of int's has two elements, like it is supposed to have, but the first child process created for the first client still has only one element, instead of two. I have no idea why and how to change the code so that the first client will also have 2 elements when the second client connects to the server. I have tried declaring the array as static, using pointers, etc, but nothing works.
Server code snippet:
Code:
...
int clients[5], i = 0;
//int * clients = (int *)calloc(5, sizeof(int));
int sd;
...
socket(...);
bind(...);
listen(...);
...
while (1) {
sd = accept(...);
clients[i] = sd;
i++;
...
if (fork() == 0) {
...
for(i = 0; i < 5; i++) {
send(clients(i), ...);
}
...
}
...
}
Any help is appreciated, thank you!