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);
}
}
From the
fork(2)manual page:This tells me that you should not close the listening socket in the child process. You shouldn’t close the accepted socket in the parent process either, but let it be closed by the child process when it’s done.