0

My system is C++ on ARM running Ubuntu.

I am having some problems with Berkley Sockets when I am trying to do a blocking read I get an error and the code is EAGAIN. I put a timer in the code and I find that the error is occurring before the socket timeout. I look at the device that I am connecting too and the socket did not close.

I don't know how this relates but it appears that that this only happens when I am running the program under gdb...at least that is the only time that I have noticed it.

Here is a simplified version of the code. I have taken out the error checking to make it smaller.

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
user846566
  • 373
  • 1
  • 3
  • 12
  • Are you sure you succeeded in setting the socket non-blocking? EAGAIN is returned on a blocking socket if the read would block. Check the return value of fcntl(). – Erik Alapää Apr 20 '15 at 13:06
  • Checked and the return value is 0...success. BTW: This error only occurs occasionally. – user846566 Apr 20 '15 at 14:15

0 Answers0