Solution:
When I migrated the game server under Windows to Linux, I encountered many problems. One of them was that select always returned 1. After continuous debugging and analysis, I found that it was originally port occupation.
Socket in LinuxProgramWhen the program is closed, the underlying TCP connection will not be closed immediately. Problems may often occur during program debugging. You can run the following command:
Netstat-APN | grep <port number>
Check whether the port you are using is in use.
If the TCP status is time_wait and your program is closed, TCP will automatically release the port after a while.
If the information you see is your program name and PID, You have to manually close the program:
Kill <pid>
Or:
Pkill <program name> (make sure there are no programs with duplicate names)
Usage of select:
Header file
# Include <sys/time. h>
# Include <sys/types. h>
# Include <unistd. h>
Define functions
Int select (int n, fd_set * readfds, fd_set * writefds, fd_set * contains TFDs, struct timeval * timeout );
Function Description
Select () is used to wait for the state change of the description word of the file. Parameter n represents the largest file descriptive word plus 1. The readfds, writefds, and limit TFDs parameters are called descriptive phrases and are used to return the reading, writing, or exception of the descriptive word. The macro below provides a way to deal with these three descriptive phrases:
Fd_clr (inr fd, fd_set * Set); used to clear the related FD bits in the description phrase set.
Fd_isset (int fd, fd_set * Set); used to test whether the bits of the related FD in the phrase set are true.
Fd_set (int fd, fd_set * Set); used to set the FD bit in the description phrase set.
Fd_zero (fd_set * Set); used to clear all bits of the phrase set.
The timeout parameter is a structure timeval used to set the select () wait time. Its structure is defined as follows:
Struct timeval
{
Time_t TV _sec;
Time_t TV _usec;
};
If the timeout parameter is set to null, the SELECT statement does not have timeout (that is, it waits until the status changes ).
Return Value
RunSuccessfulReturns the number of changes in the file descriptive word status;
IfTimeoutReturns 0, indicating that the time has exceeded the timeout before the descriptive word state changes;
WhenError-1:
Error causes exist inErrnoIn this case, the values of readfds, writefds, exceptfds, and timeout become unpredictable. Errno value:
The description of the ebadf file is invalid or the file is closed.
Eintr this call is interrupted by the signal
The value of N is negative.
Insufficient enomem core memory
Example
Common Program snippets:
Fs_set readset; fd_zero (& readset); fd_set (FD, & readset); select (FD + 1, & readset, null, null); If (fd_isset (FD, readset ){......}