webgenius
webgenius

Reputation: 904

Will the descriptors closed after fork be invalid in the other process?

I'm referring the below code snippet from this link:

while (1)
 {
   newsockfd = accept(sockfd,
               (struct sockaddr *) &cli_addr, &clilen);
   if (newsockfd < 0)
     error("ERROR on accept");
   pid = fork();
   if (pid < 0)
     error("ERROR on fork");
   if (pid == 0)
   {
     close(sockfd);
     dostuff(newsockfd);
     exit(0);
   }
   else
     close(newsockfd);
 } /* end of while */

void dostuff (int sock)
{
   int n;
   char buffer[256];

   bzero(buffer,256);
   n = read(sock,buffer,255);
   if (n < 0) error("ERROR reading from socket");
   printf("Here is the message: %s\n",buffer);
   n = write(sock,"I got your message",18);
   if (n < 0) error("ERROR writing to socket");
}

After the fork() call, there would be two processes - Parent and child.

For the parent process, the else part holds true, and so it will close newsockfd. But newsockfd is used by child process for read and write system calls in dostuff method. Won't the read and write system calls fail in this case?

Upvotes: 2

Views: 2033

Answers (2)

Viktor Latypov
Viktor Latypov

Reputation: 14467

The child process will have its own brand new 'newsockfd' in its own memory. The socket handle there will have nothing in common with the parent's 'newsockfd' which is being closed.

Upvotes: 2

Rafał Rawicki
Rafał Rawicki

Reputation: 22690

No, because during fork all open file descriptors are copied and they are not the same descriptors, they just point to the same file.

From the fork(2) manpage:

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)).

Upvotes: 8

Related Questions