int main(int argc, char **argv) { SockType st; if (argc != 3) { cout << "arguments too short" << endl; return 0; } if (strcmp(argv[1],"-l") == 0) { st = LIST; } else if (strcmp(argv[1], "-d") == 0) { st = DOWNLOAD; } else { cout << "no " << argv[1] << "argument" << endl; } int sockfd = tcp_connect(IP, PORT); if (sockfd < 0) return 1; clientHandle(sockfd, st, argv[2]); }
int main(int argc, char *argv[]) { // set the global parent ID: globalPpid = getpid(); time(&t); clientCount = 0; // counts the number of clients so far runServer = 1; // whether to continue running the server // signal handling signal(SIGINT, sigintHandler); // and the rest of the things... int portno; socklen_t clilen; int n; if (argc < 2) { fprintf(stderr,"ERROR, no port provided\n"); exit(1); } //setsockopt (sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd,5); printf("\nStarting server...\n"); while (runServer){ clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); // only now has the client been confirmed clientCount++; //write on the server side that we connected to a client, (before forking?) printf("Servicing client %i\n",clientCount); //printf("THE PID: %i, global: %i\n",(int) getpid(),globalPpid); fflush(stdout); if (n < 0) { error("ERROR on accept"); } else{ // ########### FORK HERE ############ //int fk = fork(); int pid; if((pid = fork()) == -1){ //in case of failure close(newsockfd); continue; } else if(pid == 0){ // the child process clientHandle(newsockfd); close(newsockfd); runServer = 0; break; } else{ // parent stuff? it has a duplicated reference to the socket..? close(newsockfd); continue; } } } close(sockfd); return 0; }