Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking/NSURLConnection receiving NSPOSIXErrorDomain Code=9 "The operation couldn’t be completed. Bad file descriptor"

In my app which uses AFNetworking/NSURLConnection for sending requests to the server I sometimes (very rarely) see this error in operation failure block:

Error Domain=NSPOSIXErrorDomain Code=9 "The operation couldn’t be completed. Bad file descriptor"

At https://devforums.apple.com/message/278770#278770 there's an answer to a similar question:

It means that someone has been deallocating file descriptors out from underneath NSURLConnection.

But in my own code I don't touch any streams of file descriptors in any way. It's just simple GET/POST requests.

What could be the cause of this problem?

Has someone encountered this error in their AFNetworking operations?

Also, how can I close this file descriptor deliberately if I really wanted to? The answer to this question will help me to understand the problem better.

like image 558
kolyuchiy Avatar asked Feb 27 '14 06:02

kolyuchiy


2 Answers

According to this Apple TechNote on multitasking and networking, you can get EBADF (POSIX error 9) if the app is suspended and the socket is reclaimed.

Note: When your app resumes execution the actual error returned by a socket's whose resources have been reclaimed is purposely not specified here to allow for future refinements. However, in many cases the error will be EBADF, which is probably not what you were expecting! Under normal circumstances EBADF means that the app has passed an invalid file descriptor to a system call. However, in the case of a socket whose resources have been reclaimed, it does not mean that the file descriptor was invalid, just that the socket is no longer usable.

like image 129
user102008 Avatar answered Oct 05 '22 23:10

user102008


(I don't think this is a complete answer, but I'm hoping it will be helpful and can be turned into one.)

The error you're looking at it EBADF. It's returned from operating with a closed file. But you've figured this out already. :)

Assuming you're not using the stdio library, I think what you're running into is the equivalent of an overrelease. Basically, you're handing off ownership of a file to something, which is then closing it.

You should be paying particular attention to NSFileHandle, especially to see if you or anyone is calling initWithFileDescriptor:, copying a file, etc. These could cause the NSFileHandle to take ownership of the file descriptor, which means closing it when it's deallocated.

Look less at your networking code, and more at how you're setting up the files.

like image 44
Steven Fisher Avatar answered Oct 06 '22 00:10

Steven Fisher