On Jan 10, 2011, at 3:04 PM, Jonathon Kuo wrote:

> 
> On Jan 10, 2011, at 2:58 PM, Ken Thomases wrote:
> 
>> On Jan 10, 2011, at 4:20 PM, Dave Zarzycki wrote:
>> 
>>> On Jan 10, 2011, at 2:06 PM, Jonathon Kuo wrote:
>>> 
>>>> I set up a source handler on a TCP socket like this:
>>>> dispatch_source_t newsrc = 
>>>> dispatch_source_create(DISPATCH_SOURCE_TYPE_READ,sockfd,0,globalQueue); 
>>>> 
>>>> It works well, and when a client process closes his socket my 
>>>> cancel_handler gets called, I clean up, and life is good. But if I do a 
>>>> close(sockfd) from my side, my cancel_handler doesn't get invoked. I have 
>>>> to explicitly do a dispatch_source_cancel(). Shouldn't closing the socket 
>>>> be enough to cause my cancel_handler to be run?
>>> 
>>> Jonathon,
>>> 
>>> No. This is covered in the dispatch_source_create() man page under the 
>>> section on cancelation:
>>> 
>>> Important: a cancellation handler is required for file descriptor and mach 
>>> port based sources in order to safely close the descriptor or destroy the 
>>> port. Closing the descriptor or port before the cancellation handler has 
>>> run may result in a race condition: if a new descriptor is allocated with 
>>> the same value as the recently closed descriptor while the source's event 
>>> handler is still running, the event handler may read/write data to the 
>>> wrong descriptor.
>> 
>> And, likewise, it is not safe to close a file descriptor in one thread while 
>> it is the subject of a read(), select(), kevent(), or similar in another 
>> thread.  In other words, in no system API is it safe to do what you're 
>> trying to do.
> 
> Okay... then is the only place I should ever call the close() is from within 
> the cancel_handler for that file descriptor?

Yes – your code can close() the descriptor then or thereafter. The important 
goal is that your code must know when libraries (such as GCD) are done 
borrowing the descriptor to do asynchronous work on behalf of your code. GCD 
solves this problem with cancelation callbacks.

davez_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to