If I have two threads (Linux, NPTL), and I have one thread that is polling on one or more of file descriptors, and another is closing one of them, is that a reasonable action? Am I doing something that I shouldn't be doing in MT environment?

The main reason I consider doing that, is that I don't necessarily want to communicate with the polling thread, interrupt it, etc., I instead would like to just close the descriptor for whatever reasons, and when the polling thread wakes up, I expect the revents to contain POLLNVAL, which would be the indication that the file descriptor should just be thrown away by the thread before the next poll.

I've put together a simple test, which does show that the POLLNVAL is exactly what's going to happen. However, in that case, POLLNVAL is only set when the timeout expires, closing the socket doesn't seem to make the poll() return. If that's the case, I can kill the thread to make poll() restart to return.

1 Answer
1

For Linux at least, this seems risky. The manual page for close warns:

It is probably unwise to close file descriptors while they may be in
use by system calls in other threads in the same process. Since a
file descriptor may be reused, there are some obscure race conditions
that may cause unintended side effects.

Since you're on Linux, you could do the following:

Set up an eventfd and add it to the poll

Signal the eventfd (write to it) when you want to close a fd

In the poll, when you see activity on the eventfd you can immediately close a fd and remove it from poll

Alternatively you could simply establish a signal handler and check for errno == EINTR when poll returns. The signal handler would only need to set some global variable to the value of the fd you're closing.

Since you're on Linux you might want to consider epoll as a superior albeit non-standard alternative to poll.

Don't accept my answer so quickly - this will deter other potential answerers. Wait and see if better answers come up. Click the check mark again to un-accept this answer.
–
cnicutarMay 12 '12 at 6:52

thank you, that snippet is exactly what I should've read :) Reusability will cause me problems. I can't write to the fd myself, since it will be connected to a remote, so I'll have to come up with custom signalling.
–
Pawel VeselovMay 12 '12 at 6:52