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?
No, because during
forkall open file descriptors are copied and they are not the same descriptors, they just point to the same file.From the
fork(2)manpage: