I am attempting to make a simple server so that two clients can communicate with each other. The main server code accepts the two client connections and then forks off a process that uses execl to generate a personal server between the two clients so that the main server can continue looking for new connections. Everything seems to work correctly until the personal server attempts to contact the clients and they both receive gibberish, if anyone knows what could cause this please let me know.
Main server after accepting two clients:
if(fork() == 0){
close(listener);
int nBytes;
char* playerOne[20];
char* playerTwo[20];
//Creates strings to hold file descriptor information for execl
char connAscii[sizeof(int)];
char connAscii2[sizeof(int)];
snprintf(connAscii,sizeof(conn), "%d", conn);
snprintf(connAscii2,sizeof(conn2), "%d", conn2);
fprintf(stderr, "Int conn: %d, asciiConn: %s, backToInt: %d\n", conn, connAscii, atoi(connAscii));
char *argf[2];
argf[0] = connAscii;
argf[1] = connAscii2;
fprintf(stderr, "that is to say %s and %s\n", argf[0], argf[1]);
//Send Handle Request to Connection 1
nBytes = send(conn, handleRequest, sizeof(handleRequest),0);
if(nBytes == -1){
perror("send");
exit(1);
}
//Receive Handle from Connection 1
nBytes = recv(conn, playerOne, 20, 0);
if(nBytes == -1){
perror("recv");
exit(1);
}
//Send Handle Request to Connection 2
nBytes = send(conn2, handleRequest, sizeof(handleRequest),0);
if(nBytes == -1){
perror("send");
exit(1);
}
//Receive Handle from Connection 2
nBytes = recv(conn2, playerTwo, 20, 0);
if(nBytes == -1){
perror("recv");
exit(1);
}
//Send Handle for Connection 2 to Connection 1
nBytes = send(conn, playerTwo, sizeof(playerTwo),0);
if(nBytes == -1){
perror("send");
exit(1);
}
//Send Handle for Connection 1 to Connection 2
nBytes = send(conn2, playerOne, sizeof(playerOne),0);
if(nBytes == -1){
perror("send");
exit(1);
}
//Passes file descriptors to privateServer
execl("privateServer","privateServer", connAscii, connAscii2, (char *)0);
}
Personal server invoked by execl:
char greet[] = {"Hello players, please wait for match setup."};
int main(int argc, char *argv[]) {
int conn1 = atoi(argv[1]);
int conn2 = atoi(argv[2]);
int sent;
fprintf(stderr, "Attempting connection with %d\n", conn1);
sent = send(conn1, greet,sizeof(greet),0);
if(sent == -1){
perror("send");
exit(1);
}
sent = send(conn2, greet,sizeof(greet),0);
if(sent == -1){
perror("send");
exit(1);
}
fprintf(stderr,"Hopefully they got it\n");
return 0;
}
Clients: Reading the recv buff char by char results in gibberish and printing the entire buffer doesn't show anything, but numbytes == 61.
char *buff = (char*)malloc(100);
memset(&buff[0],0,sizeof(buff));
numbytes = recv(sockfd, buff, 99, 0); //should be from private server
if (numbytes == -1) {
perror("recv");
exit(1);
}
buff[numbytes] = '\0';
int i;
for(i = 0; i < numbytes; i++){
fprintf(stderr, "%c", buff[i]);
}
printf("From match server: %.*s (%d bytes)\n", numbytes, buff, numbytes);