POLLNVAL
is set if the file descriptor number does not correspond to a file descriptor.
I don't know for sure why this behavior was chosen rather than having poll
return an error. The reason may have been ease of implementation: it allows the implementation to loop over the array of struct pollfd
a single time, without having to cope with an early return where some elements of the array would have been modified and others not.
It's also possible that the reason was programmer convenience. Since calling poll
on an invalid file descriptor is not an error, it's possible to close a file descriptor and still include it in the array. This convenience is of limited interest: you can only do this as long as you don't open any other file (because it might reuse the file descriptor), and you still pay the (tiny) performance penalty for the array element. It can be useful in a multithreaded program, where one thread may call close
while another thread is engaged in a poll
call or about to do so: this is not an error, the polling thread only needs to be notified before an open
.