polslinux
polslinux

Reputation: 1779

socket and fork with c

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:

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);
  }
}

Upvotes: 3

Views: 5491

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

From the fork(2) manual page:

The child inherits copies of the parent's set of open file descriptors. Each file descriptor in the child refers to the same open file description (see open(2)) as the corresponding file descriptor in the parent. This means that the two descriptors share open file status flags, current file offset, and signal-driven I/O attributes (see the description of F_SETOWN and F_SETSIG in fcntl(2)).

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.

Upvotes: 2

Related Questions