使用libcurl出现的段错误问题解决

1. 问题定位

在使用libcurl时出现了段错误,经过调试发现出现的时机是在断网的情况下,为了保持网络的自动恢复我会在程序中重启网络节点 ifconfig eth0 down,如果这时正在用 libcurl 做 GET 请求或者 POST 请求等就会出现段错误

2. 分析出现原因

libcurl在configure默认配置编译的情况下,它是使用alarm+siglongjmp实现域名解析超时。如果这个时候执行了 ifconfig eth0 downDNS解析会失败,然后 libcrl 会发出信号来打断等待,这个就是导致出现段错误导致程序退出的原因,真是坑啊

3. 解决办法

设置curl属性的时候添加下面的代码,屏蔽信号

/* set NOSIGNAL */
	curl_easy_setopt(hnd, CURLOPT_NOSIGNAL, 1);

4. 官网关于 CURLOPT_NOSIGNAL 的说明

CURLOPT_NOSIGNAL
Pass a long. If it is 1, libcurl will not use any functions that install signal handlers or any functions that cause signals to be sent to the process. This option is mainly here to allow multi-threaded unix applications to still set/use all timeout options etc, without risking getting signals. (Added in 7.10)
If this option is set and libcurl has been built with the standard name resolver, timeouts will not occur while the name resolve takes place. Consider building libcurl with c-ares support to enable asynchronous DNS lookups, which enables nice timeouts for name resolves without signals.
Setting CURLOPT_NOSIGNAL to 1 makes libcurl NOT ask the system to ignore SIGPIPE signals, which otherwise are sent by the system when trying to send data to a socket which is closed in the other end. libcurl makes an effort to never cause such SIGPIPEs to trigger, but some operating systems have no way to avoid them and even on those that have there are some corner cases when they may still happen, contrary to our desire. In addition, using CURLAUTH_NTLM_WB authentication could cause a SIGCHLD signal to be raised.

参考链接: 链接

猜你喜欢

转载自blog.csdn.net/gmq_syy/article/details/107984449
今日推荐