/* * Main routine ... * * Starts the child threads * */ #include #include #include #include #include #include #include #include "chat.h" #ifndef CHATINPORT #define CHATINPORT 7331 #endif #ifndef CHATOUTPORT #define CHATOUTPORT 8331 #endif int main(int argc, char *argv[]) { int in_recept, out_recept ; struct sockaddr_in servAddr ; pthread_attr_t attribThread ; pthread_t inThread, outThread ; struct ptGenericArg *inArg ; struct ptGenericArg *outArg ; void *newData ; struct chatbuff *G ; int i ; (void) pthread_attr_init(&attribThread) ; /* * Open the two sockets *before* creating the receptionist Pthreads * This is the most likely thing to fail */ if (((in_recept = socket(AF_INET, SOCK_STREAM, 0)) < 0) || ((out_recept = socket(AF_INET, SOCK_STREAM, 0)) < 0)) { fputs("Unable to create sockets\n", stderr) ; exit(1) ; /* Now this is unlikely to happen */ } servAddr.sin_family = AF_INET ; servAddr.sin_addr.s_addr = INADDR_ANY ; servAddr.sin_port = htons(CHATINPORT) ; if (bind(in_recept, (struct sockaddr *) &servAddr, sizeof(struct sockaddr_in))) { fprintf(stderr, "Unable to bind to port %d\n", CHATINPORT) ; if (errno == EADDRINUSE) fputs("Check if another server is still running\n\n" "If a server recently terminated, wait before restarting.\n", stderr) ; exit(1) ; } (void) listen(in_recept, SOMAXCONN) ; servAddr.sin_port = htons(CHATOUTPORT) ; if (bind(out_recept, (struct sockaddr *) &servAddr, sizeof(struct sockaddr_in))) { fprintf(stderr, "Unable to bind to port %d\n", CHATOUTPORT) ; if (errno == EADDRINUSE) fputs("Check if another server is still running\n\n" "If a server recently terminated, wait before restarting.\n", stderr) ; exit(1) ; } (void) listen(out_recept, SOMAXCONN) ; fprintf(stdout, "Reading connections -> %5d\n", CHATINPORT) ; fprintf(stdout, "Writing connections -> %5d\n", CHATOUTPORT) ; /* Initialize chat buffer */ if ((G = malloc(sizeof(struct chatbuff))) == NULL) { perror("malloc") ; exit(1) ; } G->nextSlot = 0 ; for (i=0; ibuff[i].status = UNUSED ; G->buff[i].size = 0 ; } if ((newData = malloc(sizeof(struct ptGenericArg))) == NULL) { perror("malloc") ; exit(1) ; } inArg = (struct ptGenericArg *)newData ; inArg->sock = in_recept ; inArg->G = G ; if (pthread_create(&inThread, &attribThread, InputRecept, newData)) { perror("pthread_create InputRecept") ; exit(1) ; } if ((newData = malloc(sizeof(struct ptGenericArg))) == NULL) { perror("malloc") ; exit(1) ; } outArg = (struct ptGenericArg *)newData ; outArg->sock = out_recept ; outArg->G = G ; if (pthread_create(&outThread, &attribThread, OutputRecept, newData)) { perror("pthread_create OutputRecept") ; exit(1) ; } pthread_join(inThread, (void **)NULL) ; pthread_join(outThread, (void **)NULL) ; }