简体   繁体   中英

Is there any way to tell that a file descriptor value has been reused?

I've got an API that is called with a file descriptor as an argument, and it internally stores some state associated with the file descriptor. Then on subsequent calls with the same file descriptor value, the previously generated state can be consulted.

This mostly works, except for the case where the calling code calls my API with a file descriptor, then closes the file descriptor, then allocates a new file descriptor (via socket() or accept() or etc) that ends up having the same integer value as the now-closed one, and then passes that new file descriptor to my API. At that point, my API does the wrong thing, because it erroneously associates the old socket's state with the new file descriptor.

One solution to this issue would be to force the calling code to notify my API whenever it closes a socket, so that my API would know to delete the associated state.... but I'd prefer not to force the user to do that, since it would be inconvenient for them and they'd be prone to forget to do it anyway.

Therefore, I'm wondering if there is any clever way to tell whether a file descriptor at time T is still associated with the same underlying structures that it was associated with at time (Tx). If I could do that, my API would be smart enough to tell when a file descriptor integer-value had been reused and do the right thing.

FWIW this code is intended to run under MacOS/X and Linux primarily, but the more portable the solution, the better.

I don't believe so.

You're better off providing wrappers for open/close that return an opaque type back to the callers. (You can also provide a function to get the underlying file descriptor out of that opaque type if necessary.)

If you don't want to wrap open/close, you can still use an opaque structure for your APIs (just make a pair of functions to create (with a file descriptor parameter) and release that structure), but indeed, your users will have to remember to release or the app will leak. (But C developer are supposed to know how to do that - malloc / free have been around for a while.)

Depending on exactly what your library provides, there are probably better alternatives, but this is what I believe is generally done for C APIs.

Side note: if you expect both your library and the user code to issue reads and writes on those sockets... be careful, that's real tricky.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM