|
|
Question : Sockets - Non-blocking read
|
|
Hi,
I tried with the following code to implelemt a non-blocking read from sockets. But this returns error while reading.
#include #include #include #include #include #include #include #include #include #include #include
int main() { int ctrlsock,datasock; struct sockaddr_in sock; char command[100]; int iores,bytesread; fd_set sockset; struct timeval tv; int valopts; socklen_t slen;
if((ctrlsock=socket(AF_INET,SOCK_STREAM,0))<0) { printf("Error Creating Socket\n"); return 0; } if(fcntl(ctrlsock,F_SETFL,fcntl(ctrlsock,F_GETFL) | O_NONBLOCK)<0) { printf("Error switching to non-blocking mode\n"); return 0; }
sock.sin_family=AF_INET; sock.sin_port=htons(21); if(inet_aton("10.2.0.111",(struct in_addr*)&sock.sin_addr)<=0) { printf("Invalid IP address\n"); return 0; } if(connect(ctrlsock,(struct sockaddr*)&sock,sizeof(sock))<0) { printf("Error connecing to server\n"); if(errno==EINPROGRESS) { printf("EINPROGRESS...\n"); tv.tv_sec=150; tv.tv_usec=0; FD_ZERO(&sockset); FD_SET(ctrlsock,&sockset); if(select(ctrlsock+1,&sockset,&sockset,NULL,&tv)<=0) { printf("Damn... Cannot open non-blocking socket!\n"); return (0); } slen=sizeof(int); if(getsockopt(ctrlsock,SOL_SOCKET,SO_ERROR,&valopts,&slen)!=0) { printf("Error with getsockopt\n"); return 0; } } } printf("Connected to Server.\n"); printf("Reading from server...\n"); do { iores=read(ctrlsock,command,99); if(iores<0) { printf("Error reading from server\n"); break; } command[iores]='\0'; printf("%s",command); printf("iores:%d\n",iores); }while(iores>=0); printf("\n"); close(ctrlsock); return 0;
}
I even tried with ioctl - FIONBIO. But that does'nt help. Can anyone tell what's wrong with the code?
|
Answer : Sockets - Non-blocking read
|
|
from the read man page
EAGAIN Non-blocking I/O has been selected using O_NONBLOCK and no data was immediately available for reading.
|
|
|
|
|