我的系统是运行Ubuntu的ARM上的C ++。
当我尝试阻塞读取时,我遇到了Berkley套接字的一些问题,我收到错误,代码是EAGAIN。我在代码中放了一个计时器,我发现错误发生在套接字超时之前。我看着我连接的设备,插座没有关闭。
我不知道这是如何相关的,但似乎只有当我在gdb下运行程序时才会发生这种情况......至少那是我注意到它的唯一时间。
这是代码的简化版本。我已经取消了错误检查以使其变小。
int optval;
struct timeval tv;
// Set up the sockaddrIn structures for the port
struct sockaddr_in controlTcpAddr;
memset(&controlTcpAddr, 0, sizeof(controlTcpAddr)); // Clear struct
controlTcpAddr.sin_family = AF_INET; // Internet/IP
controlTcpAddr.sin_addr.s_addr = inet_addr(hostIp); // IP address
controlTcpAddr.sin_port = htons(hostPort); // server port
// Create the TCP socket
myControlTcpSockDesc = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
// Establish connection
connect(myControlTcpSockDesc, (struct sockaddr *) &controlTcpAddr, sizeof(controlTcpAddr);
int flags = fcntl(myControlTcpSockDesc, F_GETFL);
int result = fcntl(myControlTcpSockDesc, F_SETFL, flags & ~O_NONBLOCK);
// Set the SO_REUSEADDR option for the socket
optval = 1;
setsockopt(myControlTcpSockDesc, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)
tv.tv_sec = 10; // 10 Secs Timeout
tv.tv_usec = 0;
setsockopt(myControlTcpSockDesc, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&tv,sizeof(struct timeval));
// try a read
cnt = read(myControlTcpSockDesc, myIncomingMsgBuf, MESSAGE_BUFFER_SIZE);
// at this point I find that 10 seconds have not expired
// (I have separate timer running that is not shown)
// cnt = -1
// errno = EAGAIN