LWN.net Logo

Fun with file descriptors

Fun with file descriptors

Posted Jun 7, 2007 16:41 UTC (Thu) by daney (subscriber, #24551)
In reply to: Fun with file descriptors by HenrikH
Parent article: Fun with file descriptors

The problem being is that if you use a mutex to protect a blocking read, you can not interrupt it by closing the file descriptor as the thread calling close would block on the mutex.

There are ways to work around the current state of things, but the problem is that they are often complex and easy to get wrong.


(Log in to post comments)

Fun with file descriptors

Posted Jun 12, 2007 15:23 UTC (Tue) by shane (subscriber, #3335) [Link]

The problem being is that if you use a mutex to protect a blocking read, you can not interrupt it by closing the file descriptor as the thread calling close would block on the mutex.

Yes, this is a tricky problem.

You can create a file descriptor that you can "wake" the blocking thread and then use select() or poll(). You can use a pipe for this (of course you have to be careful to handle closing the pipe then).

You can also use a condition variable for the reader, and a separate thread checking for input that signals the reader. A 3rd thread should be able to close the file descriptor, which should then return EBADF from it's select() or poll(). (I think...)

Sharing file descriptors between threads is indeed a pain in the ass though. Correct threaded programming is fairly difficult, it makes one wonder if maybe good old event-driven programming wasn't really the answer all along!

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds