3 ms·
The process's current directory is mutable global state as well, and yet chdir(2) is thread-safe.
by Joker_vD 2y ago
The process's current directory is mutable global state as well, and yet chdir(2) is thread-safe.
- plorkyeran 2y agochdir 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.
- fanf2 2y agoYeah 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.
- account42 2y agoIt's threadsafe in the memory sense. It's not threadsafe in the having an idea what files you are accessing sense.
- Joker_vD 2y agoThe 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.
- account42 2y agoIf 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.
- fch42 2y agoThe current working directory is kernel state. getcwd() is a system call. This doesn't compare.
- kazinator 2y agochdir 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.