Avoid reusing of the same fd number in a multithread socket application
c++, linux, multithreading, sockets
Solution
Ok, found the answer.
The best way here is to call accept() and get the lowest fd available, duplicate it with a number known by you like dup2(6,1000) and close(6), you have now control of the fd range you use.
Next accept will come again with 6 or similar, and we'll dup2(6,999); and keep decreasing like that and reseting it if it gets too low.
Since the accepting is done always in the same thread and dup2 and close aren't expensive compared to accept which is always done there it's perfect for my needs.
Problem
I have an asynchronous application executing several threads doing operations over sockets where operations are scheduled and then executed asynchronously. I'm trying to avoid a situation when once scheduled a read operation over a socket, the socket gets closed and reopened(by possibly another peer in another operation), before the first operation started execution, which will end up reading the proper file descriptor but the wrong peer. The problem comes because (accept();close();accept()) returns the same fd in both accepts() which can lead to the above situation. I can't see a way of avoiding it. any hint?