I have a server made of a master and some slaves (one for the example)
I would like the master to distribute clients on connection.
//Initialisation
struct sockaddr_in clientaddr;
socklen_t clientlen;
clientlen = (socklen_t)sizeof(clientaddr);
int listenfd = Open_listenfd(PORT);
//Children instanciation here
int pipe_in = 0;
for (int i = 0; i < NPROC; i++)
{
int p[2];
pipe(p);
children[i].id=Fork();
if(children[i].id == 0){
close (p[1]);
pipe_in=p[0];
goto CHILDREN;
}
else{
close (p[0]);
children[i].pipe_to = p[1];
}
}
//Master Loop
int curchild = 0;
while (1) {
int connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
write(children[curchild].pipe_to, &connfd, sizeof(connfd));
printf("Sent to slave %d\n",connfd);
curchild = Next(curchild);
}
return 0;
//Slave Process
CHILDREN :
while (1) {
int connfd;
read(pipe_in, &connfd, sizeof(connfd));
printf("Receveid from master %d\n",connfd);
Rio_writen(connfd, "Test\n", 5);
Close(connfd);
}
Here the descriptor sent and receiveid are similar, but the Rio_writen
returns an error : Bad file descriptor