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信号


ios signal SIGPIPE 闪退问题的处理_第1张图片
image

完美解决。


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

    加上 [SignalHandler RegisterSignalHandler]; 即可

你可能感兴趣的:(ios signal SIGPIPE 闪退问题的处理)