问题
I'm aware what a working directory (wd) is and it's purpose (for writing software at least).
What I don't understand is the ownership of the wd. Furthermore, I want to understand how the answer may vary between operating systems so any clarification on unusual behaviour on a particular OS would be appreciated.
So firstly, where does the wd manifest itself? Is it within a process, and all threads created by that process share the same wd? If the wd gets modified by thread 'A', is the change instantly visible to thread 'B' which was also spawned by thread 'A's process?
And secondly, how is the wd initially defined? If you start something from a command prompt its fairly easy to see how, but what about a process which spawns several more processes?
Note: Process Explorer shows each process' wd in it's Properties window.
回答1:
On most modern operating systems, the working directory is a property of the process. When a parent process forks a child process, it will (by default) have the same working directory. This behaviour can usually be overriden by explicitly specifying a working directory.
Once forked, the child's working directory field is independant of the parent. A change of the parent's working directory should not alter the child process. The behaviour of duplicating any handles or security tokens related to the working directory is highly dependant on the operating system.
On Windows, CreateProcess
adds an RTL_USER_PROCESS_PARAMETERS structure to the memory of the process, which contains UNICODE_STRING CurrentDirectoryPath
and HANDLE CurrentDirectoryHandle
. The structure is always loaded at 0x20000
on existing NT versions of Windows, but this may change in future.
回答2:
Commonly, the present working directory is a per-process construct, so all threads within a process share a single PWD and a chdir instantly propagates to the other threads. (On Linux, it is possible to create threads with their own PWD using the low-level clone system call.)
The PWD is inherited from the parent of a process. How many sibling processes there are doesn't matter; they'll all share their initial PWD.
来源:https://stackoverflow.com/questions/9082804/precisely-what-owns-the-current-working-directory