I can find a lot of documentation on using chdir()
to change a directory in a program (a command shell, for instance). I was wondering if it is possible to somehow do the same thing without the use of chdir()
. Yet, I can't find any documentation or examples of code where a person is changing directories without using chdir()
to some capacity. Is this possible?
CodePudding user response:
In Linux, chdir()
is a syscall. That means it's not something a program does in its own memory, but it's a request for the OS kernel to do something on the program's behalf.
Granted, it's one of two syscalls that can change directories -- the other one is fchdir()
. Theoretically you could use the other one, though whether that's what your professor actually wants is very much open to interpretation.
In terms of why chdir()
and fchdir()
can't be reimplemented by an application but need to be leveraged: The current working directory is among the process state maintained by the kernel on a program's behalf; the program itself can't access kernel memory without asking the kernel to operate on its behalf.
Things are syscalls because they need to be syscalls -- if something could be done in-process, it would be done that way (crossing the boundary between userspace and kernelspace involves a context-switch penalty; it's not without performance impact). In this case, letting the kernel do accurate bookkeeping as to what a process's working directory is ensures that the working directory is maintained when a new executable is loaded (with execve()
), and helps to ensure the integrity of the kernel's records (making sure a program can't pretend to have its current working directory be a directory it doesn't actually have access to).