/* Sivann '99 */ #include #include #include #include #include #include #include #include #include int numofchildren=0; void childhdl(int); serve_client(int Asd) { fd_set inout_fds; char buff[1024]; int r,i; while (1) { FD_ZERO(&inout_fds); FD_SET(Asd, &inout_fds); i=select(64,&inout_fds,(fd_set *) 0, (fd_set *) 0, (struct timeval *) 0); if (FD_ISSET(Asd,&inout_fds)) { r=read(Asd,buff,1024); buff[r]=0; printf("Read:%s\n",buff); if (r<=0) { shutdown(Asd, 2); close(Asd); printf("serve_child:closed socket..exiting\n"); exit(0); } sprintf(buff, "Hello\n"); write(Asd, buff, strlen(buff)); } else printf("Select interrupted (?)\n"); } } void childhdl(int pid) { int i,r; while((r=waitpid(-1,&i,WNOHANG))>0) numofchildren--; #ifdef DEBUG printf("\n%d:childhandler:child %d died,childrens:%d \n",getpid(), r, numofchildren); #endif signal(SIGCHLD, childhdl); } main(int argc,char **argv) { int one = 1, i; struct sockaddr_in sa; char buff[1024]; int Asd, len, lsd; fd_set inout_fds; int port; if (argc!=2) { fprintf(stderr,"Usage: musicserver \n"); exit(0); } port=atoi(argv[1]); if ((lsd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } setsockopt(lsd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one)); sa.sin_family = AF_INET; sa.sin_port = htons((u_short) port); sa.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(lsd, (struct sockaddr *) & sa, sizeof(sa)) < 0) { perror("bind"); exit(2); } if (listen(lsd, 1) < 0) { perror("listen"); exit(3); } len = sizeof(sa); signal(SIGCHLD, childhdl); while (1) { FD_ZERO(&inout_fds); FD_SET(lsd, &inout_fds); do { i=select(64,&inout_fds,(fd_set *) 0, (fd_set *) 0, (struct timeval *) 0); } while (i<0); if (FD_ISSET(lsd,&inout_fds)) { if (fork()) { numofchildren++; printf("New connection, childrens:%d\n",numofchildren); } else { /*child*/ if ((Asd = accept(lsd, (struct sockaddr *) & sa, &len)) < 0) { perror("accept"); exit(4); } printf("Accepted\n"); sprintf(buff, "Hello there\n"); write(Asd, buff, strlen(buff)); serve_client(Asd); printf("serve_client %d exited\n",getpid()); exit(0); } /*child*/ } } /*while (1) */ }