iOS signal SIGPIPE 闪退问题的处理

今天维护旧项目的时候碰到一个闪退问题:
手机锁屏,再开屏,App就闪退了。
xcode的断点:
image
度娘的原因是:

在使用socket的send函数时,如果此时服务器断开连接,socket将会收到broken pipe的错误,如果不忽略或者处理这个信号,App会crash掉。

官方文档的解决方法:

When a connection closes, by default, your process receives a SIGPIPE signal. If your program does not handle or ignore this signal, your program will quit immediately. You can handle this in one of two ways:
● Ignore the signal globally with the following line of code:
signal(SIGPIPE, SIG_IGN);
● Tell the socket not to send the signal in the first place with the following lines of code (substituting the variable containing your socket in place of sock):
int value = 1;
setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
For maximum compatibility, you should set this flag on each incoming socket immediately after calling accept in addition to setting the flag on the listening socket itself.

看了一脸懵逼,不知道该加在哪里。

然后看到了这个大神的文章:https://www.cnblogs.com/daxiaxiaohao/p/4466097.html

在捕捉到异常的回调方法里加上 signal(SIGPIPE, SIG_IGN);

忽略signal SIGPIPE信号


image

完美解决。


啰嗦下用法,在
  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    加上 [SignalHandler RegisterSignalHandler]; 即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • 用canvas绘制一个时钟是件非常简单的事情,自己尝试用下面向对象的方式去绘制时钟,会使这段代码的复用性更好. 这...
    土豪码农阅读 247评论 0 1
  • 一周过去,上周这个时候在北戴河海边写周检视,这周上了两天易效能的线下课,在家里写周检视,早上跑步的时候,凉风拂面,...
    神仙洋洋阅读 151评论 0 0
  • 减肥失败的小伙伴们、拖延癌晚期患者、正在为计划搁浅负罪感满格的童鞋们,把你们的碗洗干净放好,“蚁鹅”牌2017第一...
    椬yi阅读 707评论 0 0
  • Introduction Remona is a yearthree college student. She i...
    雷默君阅读 1,752评论 3 2