This answer summarizes the solution found by the OP, and comments by rob mayoff and Joseph Quinsey.
If a program is not reusing a file descriptor (what you called a 'socket id'), it is not closing the file descriptor. Try running lsof
on your test program when it's been running for a while. You will probably find many open sockets in the output. (But the OP says lsof -g PID
doesn't seem to work on debugged process).
Alternatively, try netstat -a -p --inet | grep process-name-or-pid
.
On some systems, sometimes a simple close(fd)
for a socket is not sufficient. If your socket file descriptors are constantly increasing, then the answer close() is not closing socket properly might help.
To avoid the problem with FD_SETSIZE, several writers, for example Increasing limit of FD_SETSIZE and select, suggest using poll
rather than select
.
Finally, the OP solved the issue:
It turned out there was socket leak in another place, which violate destructor should release all resource. And this made the socket id increase. Fixed, the operating system will reuse the socket id.
But anyway, the discussion is helpful, and the
FD_SET
is bad design, and we should usingpoll()
.
Note that Unix-like systems always (or usually) use the smallest available file descriptor. For example, the man page for open(2)
states;
The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.