Search code examples
cunixnetwork-programming

Socket duplication when forking a process in C


I'm learning network programming and trying to implement a HTTP server. I'm following a guide on socket programming in C (https://beej.us/guide/bgnet/html/split/client-server-background.html) and came across this example:

while(1) {  // main accept() loop
    sin_size = sizeof their_addr;
    new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
    if (new_fd == -1) {
        perror("accept");
        continue;
    }

    inet_ntop(their_addr.ss_family,
        get_in_addr((struct sockaddr *)&their_addr),
        s, sizeof s);
    printf("server: got connection from %s\n", s);

    if (!fork()) { // this is the child process
        close(sockfd); // child doesn't need the listener
        if (send(new_fd, "Hello, world!", 13, 0) == -1)
            perror("send");
        close(new_fd);
        exit(0);
    }
    close(new_fd);  // parent doesn't need this
}

The part I am confused about is the forking of processes.

Why do we close the original socket file descriptor (sockfd) when it was only created in the original parent process? Or more generaly, are all of the resources created by the parent process duplicated in the child - as for example the socket file?


Solution

  • Because according to the POSIX specification of fork().

    The child process shall have its own copy of the parent's file descriptors [...].

    The spirit behind fork() is that process resources are duplicated although this is not 100% true as threads aren't duplicated.