使用信号SIGALRM 为 connect 设置超时
1 #include"apue.h" 2 typedef void Sigfunc(int); 3 //void (*signal(int signo,void (*func)(int)))(int); 4 static void connect_alarm(int); 5 int connect_timeout(int sockfd,(SA*)pserveraddr,socklen_t len,int sec) 6 { 7 signal(SIGALRM,connect_alarm); 8 int res; 9 Sigfunc * sigfunc=alarm(sec); //sigfunc restore old sig function 10 if((res=connect(sockfd,pserveraddr,len))<0) 11 { 12 if(errno==EINTR) 13 { 14 fprintf(stderr,"time out!\n"); 15 errno=ETIMEOUT; 16 close(fd); 17 return n; //-1 connection error; 18 } 19 } 20 else 21 { 22 alarm(0); 23 signal(SIGALRM,sigfunc); //restore old sigfunction 24 return n; // 0 connection success! 25 } 26 27 }
static void connect_alarm(int) { return ; }