Here a piece of my fork-server code:
signal (SIGINT, ( void *)sig_handler);
while(1){
memset(&cli_addr, 0, sizeof(cli_addr));
if((newsockd = accept(sockd, (struct sockaddr *) &cli_addr, (socklen_t *) &socket_len)) < 0){
perror("Errore nella connessione\n");
onexit(newsockd, sockd, 0, 2);
}
fprintf(stdout, "Ricevuta richiesta di connessione dall' indirizzo %s\n", inet_ntoa(cli_addr.sin_addr));
child_pid = fork();
if(child_pid < 0){
perror("Fork error");
onexit(newsockd, sockd, 0, 2);
}
if(child_pid == 0){
do_child(newsockd);
}
else{
attended_pid = waitpid(child_pid, NULL, 0);
if(attended_pid != child_pid){
printf("Child error");
}
}
}
My question is: have i to close the main sock (sockd) before executing the client?
I think no but:
- i've added a "sigint controller" and if i press CTRL-C on the server (with commented sockd ->
//close(sockd);) the sigint will be executed 3 times with 2 concurrent connection (why??) - if i have this code
close(sockd)the sigint will be executed only 1 time but i got an:bad file descriptoron theacceptinstruction.
So, what have i to do?
Thanks!
PS: my sigint code:
void sig_handler(const int signo, const int sockd, const int newsockd){
if (signo == SIGINT){
printf("Ricevuto SIGINT, esco...\n");
if(newsockd) close(newsockd);
if(sockd) close(sockd);
exit(EXIT_SUCCESS);
}
}
0is a valid socket/file descriptor. So you should better initialize an unused socket/file descriptor to-1before usage and after havingclose()ed it and then use-1to test if it's a valid one or not. - alkwaitpidat regular intervals to clean up after your children. - Some programmer dudemultiple sigintproblem is still here :( - polslinux