Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is scandir really thread safe?

In the UNIX® System Threads Reference, under the heading of "Thread-safety" is a list of functions are "not guaranteed to be thread-safe on all UNIX systems." The function scandir() is absent from this list, while readdir() appears on the list.

However the glibc source for scandir() clearly appears to call readdir(), not the thread-safe readdir_r(). So was scandir() omitted from the list for some other reason, or is it thread-safe for some reason I am missing?

like image 941
Mike Godin Avatar asked Nov 01 '22 10:11

Mike Godin


2 Answers

I think, this list covers POSIX functions only. scandir(3) is BSD/SVID and might not be listed there hence. The new, thread-safe functions are probably the focus of this list but not listing old, thread-unsafe functions.

like image 146
ensc Avatar answered Nov 09 '22 12:11

ensc


It appears that POSIX.1-2008 specifies that scandir() is thread-safe, since it is a POSIX.1-2008 function, and not in the list of functions allowed to be non-threadsafe. However, POSIX.1-2008 does not preclude readdir() from being thread-safe, and in the case of glibc, it appears that the readdir() source actually is thread-safe, since it does not return a global struct dirent, rather it returns a glibc-defined member of the DIR type returned in the opendir() call.

So even though glibc's scandir() calls readdir(), it still appears to be thread-safe.

like image 41
Mike Godin Avatar answered Nov 09 '22 12:11

Mike Godin