标签:alarm sea bre char arc libc sigma struct 堆栈
现网有些DNS服务器质量不好,经常不返回,导致服务器在做DNS请求时经常被卡住,简单测试后发现如果服务器不返回结果,一般20+秒超时。static sigjmp_buf jmpbuf;
static void alarm_func(int sig_no)
{
siglongjmp(jmpbuf, 1);
}
struct hostent *gngethostbyname(const char *HostName, int timeout)
{
struct hostent *lpHostEnt;
signal(SIGALRM, alarm_func);
if(sigsetjmp(jmpbuf, 1) != 0)
{
alarm(0);//timout
signal(SIGALRM, SIG_IGN);
return NULL;
}
alarm(timeout);//setting alarm
lpHostEnt = gethostbyname(HostName);
signal(SIGALRM, SIG_IGN);
return lpHostEnt;
}
在实验离职里面非常好用,但是在实际代码中发现出现了异常
Thread 22 (Thread 0x7fffccff9700 (LWP 25722)):
#0 0x00000038b7addfc3 in poll () from /lib64/libc.so.6
#1 0x00000038b960bed4 in __libc_res_nsend () from /lib64/libresolv.so.2
#2 0x00000038b960876a in __libc_res_nquery () from /lib64/libresolv.so.2
#3 0x00000038b9608d29 in __libc_res_nquerydomain () from /lib64/libresolv.so.2
#4 0x00000038b96099cf in __libc_res_nsearch () from /lib64/libresolv.so.2
#5 0x00007fffec5f62d8 in _nss_dns_gethostbyname3_r () from /lib64/libnss_dns.so.2
#6 0x00007fffec5f650e in _nss_dns_gethostbyname_r () from /lib64/libnss_dns.so.2
#7 0x00000000ffffffff in ?? ()
#8 0x0000000000000002 in ?? ()
#9 0x0000000000000005 in ?? ()
#10 0x0000000000205098 in ?? ()
#11 0x0000000000000000 in ?? ()
发现子线程的堆栈变成了??? 而主线程的堆栈变成了子线程的堆栈。
研究发现,应该是gethostbyname是在子线程调用的,而信号是主线程处理,导致子线程备份的堆栈内容被覆盖到了主线程里,引起了问题。
在主线程里屏蔽掉SIGALRM信号
sigset_t mask,oldmask;
sigemptyset(&mask);
sigaddset(&mask,SIGALRM);
pthread_sigmask(SIG_BLOCK,&mask,&oldmask);
在子线程里解锁对信号的屏蔽
sigset_t mask,oldmask;
sigemptyset(&mask);
sigaddset(&mask,SIGALRM);
pthread_sigmask(SIG_UNBLOCK,&mask,&oldmask);
继续运行,一些正常,可以按照配置的超时时间结束系统函数的阻塞。
标签:alarm sea bre char arc libc sigma struct 堆栈
原文地址:http://blog.51cto.com/xzq2000/2169955