开发者

write() causes fatal crash when filedescriptor becomes invalid

I'm writing an iPhone Ap开发者_C百科p with a webserver in it. To handle a web request, I take the web request and write() to it the data that I want to send back.

When I try to download a moderately sized file (3-6MB) it works fine, but if I cancel the download halfway through, the app crashes and leaves no trace of an error. I'm thinking that the file descriptor becomes invalid halfway through the write, and causes the crash. I really don't know if this is what causes the crash, i'm just assuming.

I'm basing my webserver off of this example.

NSString *header = @"";
NSData *data = [NSData dataWithContentsOfFile:fullPath];
write (fd, [header UTF8String], [header length]);
write(fd, [data bytes], [data length]);
close(fd);

Does anyone know how to fix this? I was thinking about chunking the data and then writing each part, but I don't think it would help.


It sounds like your application is probably receiving the signal SIGPIPE as a result of attempting to write to a broken socket. You will need to ignore the SIGPIPE signal in your code, using something like:

#include <signal.h>

signal (SIGPIPE, SIG_IGN);

I suggest that you do this at the top of your main() function.

Also, you might be better off using NSInputStream/NSOutputStream or their Core Foundation counterparts, CFReadStream/CFWriteStream, since they can be made to use the run-loop to allow asynchronous operation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜