Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

292
Vistas
How to correctly use socket close for fork?

I have questions about how to correctly close the socket file descriptor. Let's assume the server forks another procedure whenever it accepts a new connection. The original socket file descriptor is sockfd and the new socket file descriptor is new_sockfd.

sockfd = socket(...)
bind(...);
listen(...);

while(1) {
  new_sockfd = accept(...);
  if(fork() == 0) {
    // Child process
    dosomething(...);

  }
  else {

  }
}

My question is, where we should put close(sockfd) and close(new_sockfd). I have seen some examples in the website (http://www.tutorialspoint.com/unix_sockets/socket_quick_guide.htm "Handle Multiple Connection") they put close(sockfd) inside the if block and close(new_sockfd) in the else block. But, after the fork, aren't the two processes running in parallel? If parent process closes the new_sockfd, won't it affect the child process to handle the socket? Also, if child process executes close(sockfd), won't this affect the entire socket program?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

When a process forks, file descriptors are duplicated in the child process. However, these file descriptors are distinct from each other. Closing a file descriptor in the child doesn't affect the corresponding file descriptor in the parent, and vice versa.

In your case, since the child process needs the accepted socket new_sockfd and the parent process continues to use the listening socket sockfd, the child should close(sockfd) (in your if block; this doesn't affect the parent) and the parent should close(new_sockfd) (in your else block; this doesn't affect the child). The fact that the parent and child are running at the same time doesn't affect this.

over 4 years ago · Santiago Trujillo Denunciar

0

The parent should close the accepted socket (in the else block): it remains open in the child process until the child is done with it, at which point it should issue its own close.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda