views:

88

answers:

2

When a program accesses files, uses system(), etc., how and where is the current working directory of that program physically known/stored? Since logically the working directory of a program is similar to a global variable, it should ideally be thread-local, especially in languages like D where "global" variables are thread-local by default. Would it be possible to make the current working directory of a program thread-local?

Note: If you are not familiar with D specifically, even a language-agnostic answer would be useful.

+7  A: 

Current directory is maintained by the OS, not by language or framework. See description of GetCurrentDirectory WinAPI function for details.

From description:

Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.

Eugene Mayevski 'EldoS Corp
+1: Also the OS isn't even required to *have* a current directory. Or even have directories at all. The 'filesystem' could be a key/value DB that lets you put colons, slashes and back-slashes in the keys just for the fun of it but does not actually care.
Zan Lynx
+4  A: 

On Linux, each process is represented by a process descriptor - a task_struct. This structure is defined in include/linux/sched.h in the kernel source.

One of the fields of task_struct is a pointer to an fs_struct, which stores filesystem-related information. fs_struct is defined in include/linux/fs_struct.h.

fs_struct has a field called pwd, which stores information about the current working directory (the filesystem it is on, and the details of the directory itself).

Richard Fearn