/* chatserver.c - a simple chat demo * (based on echoserveri.c) */ #include "csapp.h" void chat_receive(int connfd); void chat_send(int connfd); int main(int argc, char **argv){ int listenfd, connfd; pid_t pid; socklen_t clientlen; struct sockaddr_storage clientaddr; /* Enough space for any address */ char client_hostname[MAXLINE], client_port[MAXLINE]; if (argc != 2) { fprintf(stderr, "usage: %s \n", argv[0]); exit(0); } listenfd = Open_listenfd(argv[1]); while (1){ printf("Waiting for client connection ... \n"); clientlen = sizeof(struct sockaddr_storage); connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen); Getnameinfo((SA *) &clientaddr, clientlen, client_hostname, MAXLINE, client_port, MAXLINE, 0); printf("Connected to (%s, %s)\n", client_hostname, client_port); if (pid = Fork()){ // -- parent -- chat_receive(connfd); // loop: receive lines, write to terminal // done when other end closes connection kill(pid, SIGINT); // get rid of child (which is reading user input) // TODO: reap children with waitpid ? Close(connfd); // ... and continue, waiting for the next connection. } else { // -- child -- chat_send(connfd); // loop: send user input to remote process // stopped by parent after other end stops sending } } // end while(1) // The while(1) is an infinite loop, so we never get here. // To quit the program, type control-C. exit(0); }