0

I have been searching for a code for implementing the cd command using C in my own shell. However, every code uses the chdir() inbuilt function of C to change the directory. I wanted to know how I can implement cd without using chdir(). Or atleast the code for chdir() itself.

  • Why can't you use `chdir()`? – James Brown Mar 02 '20 at 13:15
  • My Professor wants us to do the whole thing from scratch. Or atleast know how exactly do the inbuilt functions work (that is why i need the code for chdir). – Shraddha Nair Mar 02 '20 at 13:17
  • 1
    `chdir` only changes the current directory. So your shell must maintain a variable that is the "current dir". Any `cd` command now changes this variable; anything needing the current dir uses this variable. That's all. – Paul Ogilvie Mar 02 '20 at 13:20
  • *My Professor wants us to do the whole thing from scratch.* You **can't** change the current working directory of your process without making the `chdir()` call (on just about all systems, anyway). The current working directory is a property of the process, and it can only be changed by the kernel - which means you have to call `chdir()`. The best you can do is (maybe) do the system call directly (if that's possible in your OS). – Andrew Henle Mar 02 '20 at 13:23
  • 1
    What @PaulOgilvie said or use `fchdir()`. – James Brown Mar 02 '20 at 13:27
  • It depends on what your shell should be able to do. If you care only about the interpretation of relative file names you might be able to replace the effect of `chdir` by converting all relative file names to absolute ones based on your own "current directory" variable. – Bodo Mar 02 '20 at 13:30
  • Remember, you can't use `printf` or `putchar` or `write` either, because it's from scratch. – user253751 Mar 02 '20 at 13:40

1 Answers1

2

You cannot. The current directory for a process is maintained by the kernel, so you need a syscall to change it.

b0fh
  • 1,678
  • 12
  • 28