Joker_vD parent
The process's current directory is mutable global state as well, and yet chdir(2) is thread-safe.
It's threadsafe in the memory sense. It's not threadsafe in the having an idea what files you are accessing sense.
The latter is always true even when you don't use chdir(2) and/or always use absolute file paths since, you know, there are other processes that can re-arrange the file system whatsoever way the like. The file system is one example of the unavoidable global mutable shared state (another example is network) which one simply has to deal with.
If files end up in a different directory because the user rearranged the filesystem under your nose, that's on the user. Most applications would deal with that by telling the user not to do that.
If your sensitive logs end up in the webserver root because one thread used chdir to temporarily change the working directory it's on the application writer.
Or to put it another way, the filesystem as a whole being shared mutable state does not make the current working directory being shared mutable state between threads any less of an issue.
chdir is thread-safe, but interacting with the current directory in any context other than parsing command-line arguments is still nearly always a mistake. Everything past a program's entry point should be working exclusively in absolute paths.
Yeah if you chdir() in a multithreaded program, all cwd-relative file accesses in other threads are fucked.
As well as absolute paths, it’s ok to work with descriptor-relative paths using openat() and friends.
chdir is only thread safe to the extent that corruption won't occur.
If one thread is using relative paths, and another is doing a chdir-based traversal (as using the nftw function, for instance), that first thread's accesses are messed up.
This is why POSIX now has various -at functions; the provide stable relative access.
The current working directory is kernel state. getcwd() is a system call. This doesn't compare.