Are there any platforms where using structure copy on an fd_set (for select() or pselect()) causes problems?

Since struct fd_set is just a regular C structure, that should always be fine. I personally don’t like doing structure copying via the = operator, since I’ve worked on plenty of platforms that didn’t have access to the normal set of compiler intrinsics. Using memcpy() explicitly rather than having the compiler insert a function call is a better way to go, in my book.

From the C spec, section 6.5.16.1 Simple assignment (edited here for brevity):

One of the following shall hold:

  • the left operand has a qualified or unqualified version of a structure or union type compatible with the type of the right;

In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.

If the value being stored in an object is read from another object that overlaps in any way the storage of the first object, then the overlap shall be exact and the two objects shall have qualified or unqualified versions of a compatible type; otherwise, the behavior is undefined.

So there you go, as long as struct fd_set is a actually a regular C struct, you’re guaranteed success. It does depend, however, on your compiler emitting some kind of code to do it, or relying on whatever memcpy() intrinsic it uses for structure assignment. If your platform can’t link against the compiler’s intrinsic libraries for some reason, it may not work.

You will have to play some tricks if you have more open file descriptors than will fit into struct fd_set. The linux man page says:

An fd_set is a fixed size buffer. Executing FD_CLR() or FD_SET() with a value of fd that is negative or is equal to or larger than FD_SETSIZE will result in undefined behavior. Moreover, POSIX requires fd to be a valid file descriptor.

As mentioned below, it might not be worth the effort to prove that your code is safe on all systems. FD_COPY() is provided for just such a use, and is, presumably, always guaranteed:

FD_COPY(&fdset_orig, &fdset_copy) replaces an already allocated &fdset_copy file descriptor set with a copy of &fdset_orig.

Leave a Comment