[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

setsockopt problem



Hi All

As a followup to my prior post regarding setsockopt():  I am a bit in 
trouble.  I have a program that uses setsockopt() to set a timeout on a 
AF_INET socket.  A subsequent read, however, blocks forever.  The 
program is multithreaded and a global signal handler has been setup to 
ignore all signals.

The OS is 3.4-current as of yesterday and this is my code:

	int fd, datfd;
	int try;
	int nread;
	socklen_t n;
	int res;
	FILE *fp, *datfp, *filefp;
	unsigned short port;
	struct sockaddr_in server_sockaddr, data_sockaddr;
	struct timeval tv;
	struct hostent *hostent;
	char buf[MAXBUF];
	char *p, *q;
		
	if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
		syslog(LOG_ERR, "unable to obtain network");
		return -1;
	}

   	/* skip socket initalization and connect */


	tv.tv_sec = 2;
	tv.tv_usec = 42L;

	printf("sizeof tv: %d\n", sizeof(tv));
		
	printf("set timeout to %ld sec, %ld usec\n", tv.tv_sec, tv.tv_usec);
		
	if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, (socklen_t) sizeof(tv)))
		syslog(LOG_ERR, "an't set receive timeout on socket, %m");
			
	if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, (socklen_t) sizeof(tv)))
		syslog(LOG_ERR, "can't set send timeout on socket, %m");
	}
		

	printf("now waiting for data...\n");

	if (getsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, &n))
		syslog(LOG_ERR, "can't set receive timeout on socket, %m");
	
	printf("sec=%ld, usec=%ld\n", tv.tv_sec, tv.tv_usec);
	
	/* The following read blocks forever */

	if ((nread = read(fd, buf, sizeof(buf))) == -1 || nread == 0) {
		printf("timeout\n");
		syslog(LOG_ERR, "no response, %m");
		close(fd);
		return -1;
	}
	
	close(fd);

Any idea what I am doing wrong here?

Thanks,
Marc