I'm creating a program which recursively finds all #include dependencies between C files in a specified directory and its child directories. Dependency paths should be absolute, so I use realpath to resolve relative paths and symbolic links. Since there can be many files I have decided to make the program multithreaded with OpenMP or pthreads.
The problem is that realpath resolves paths through the working directory. All threads share the same working directory so I would need to put a mutex on chdir and realpath.
Is there any alternate standard function to realpath which also takes the directory to resolve the path from as an argument?
There are a number of POSIX functions with the
at
suffix (such asopenat()
) which work with a specified directory. There isn't, however, arealpathat()
function in POSIX. There also isn't anopendirat()
, but there isfdopendir()
which creates aDIR
stream for an open directory file descriptor.In a multithreaded program, any use of
chdir()
is fraught.You should rethink your algorithm to use the various
*at()
functions to avoid needing to change directory at all. You'd open the directories for reading (open()
oropenat()
withO_DIRECTORY
, perhaps — thoughO_DIRECTORY
isn't 100% necessary, nor is it supported on macOS) so that you can then access the files appropriately using the directory file descriptor in the*at()
calls.