Avoid reusing the same fd number in a multi-threaded socket application

I have an asynchronous application that executes multiple threads that perform operations on sockets, where operations are performed and then executed asynchronously.

I try to avoid the situation when, after a scheduled read operation on a socket, the socket closes and reopens (possibly by another partner in another operation), before starting the first operation that ends reading the correct file descriptor, but the wrong one is wrong.

The problem arises because (accept (); close (); accept ()) returns the same fd in both accepts (), which may lead to the indicated situation.

I see no way to avoid this.

any clue?

+5
source share
6 answers

Ok, I found the answer.

The best way here is to call accept () and get the lowest fd, duplicate it with the number you know as dup2 (6,1000) and close (6), now you control the range of fd that you use.

Further accept will come again with 6 or similar, and we will dup2 (6999); and keep decreasing in the same way and republishing it if it gets too low.

Since the reception is always performed in the same thread, and dup2 and close are not expensive compared to the acceptance that is always done there, it is ideal for my needs.

+3
source

How do you control sockets? It looks like you have several threads, each of which can:

  • accept incoming connection
  • close existing connection

, , . , , , , , , , ?

+2

5- {local-addr, local-port, remote-addr, remote-port, proto}, , fd /, fd.

close()/accept() (?),

+1

! , .

, , , close(), , . shutdown() . () , .

+1

dup2() fd. , dup2() ; - , -, 1000 .

, , , dup() ( dup2()) . ( , per-fd , .)

+1

(/ ..) , . , , . , shutdown , , 0.

0

All Articles