I've already written a simple chat client, and now I'm trying to write a server that will accept messages from multiple clients at once (using the fork() command). I've been reading up on it and have tried the following code in my main, but even after a client is opened the server just sits there waiting for a connection. Am I missing something obvious?
Code:
main(int argc, char *argv[]) {
int s = MakeServerSocket(7654);
while (1) {
struct sockaddr_in sa;
int sa_len = sizeof(sa);
int fd = accept(s, (struct sockaddr *) &sa, (unsigned int *)&sa_len);
errorCheck(fd,"No connection");
int pid = fork();
errorCheck(pid, "Forking error"); //error if pid == -1
if (pid == 0) { //child process
close(s); //close original listening socket
chat(fd); //read/write from client
close(fd); //close socket
exit(1);
}
if (pid > 0) {
int x;
waitpid(-1,&x,WNOHANG); //waits 'till child has exited
close(fd); //closes parent
}
}