closedir(3) handling NULL

Jilles Tjoelker jilles at
Fri Jan 24 13:24:39 UTC 2014

On Thu, Jan 23, 2014 at 07:41:05PM -0600, Bryan Drewery wrote:
> I found that Linux handles closedir(NULL) fine and returns EINVAL. POSIX
> [1] specifies that EBADF should be returned if "The dirp argument does
> not refer to an open directory stream"

> [1]

> I've updated fdclosedir(3) as well to behave the same.

> I'll also update the manpage if there is no objection.

If you do this, it is to improve compatibility with poorly written
software and not for POSIX compliance. POSIX only permits passing null
pointers where explicitly specified (e.g. time()); otherwise, passing a
null pointer is undefined behaviour like passing any argument outside
the required domain.

On another note, I don't understand when the condition
[EBADF] The dirp argument does not refer to an open directory stream.
can actually apply. As far as I understand, only valid open directory
streams (opendir() has been called and closedir() has not been called)
may be passed to closedir() and other functions. If the pointer is not a
null pointer, detecting whether it refers to a valid open directory
stream is not possible using common methods (you could maintain a list
of directory streams but doing that is against the spirit of C and I am
quite sure that POSIX did not intend to require implementations to do

In the current code in FreeBSD, [EBADF] may also happen if an
application closes a directory stream's file descriptor from under it
and no other file descriptor is opened in its place.

In some cases like the file_name argument to realpath(), NULL is
specified to cause an [EINVAL] return; I think we are stuck with that
but should not add more such cases. Note that this [EINVAL] return also
means that realpath(NULL, p) is valid to do and should not trigger
undefined behaviour detectors.

Jilles Tjoelker

More information about the freebsd-standards mailing list