Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

290
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!