2

After a bit of research I realized that the cd system command does not have any implementation files on my system, specifically in /bin/. A class project recently required the implementation of a basic shell program that could make use of the implementation files located in this directory.

Consequentially, my program cannot change directories since cd does not exist and must have been an internal implementation by other shells.

That being said, how would you go about programmatically changing the current working directory of a program?

sherrellbc
  • 4,650
  • 9
  • 48
  • 77

1 Answers1

11

Each individual process has a notion of its "current directory". When a new process gets created, its current directory is its parent process's current directory.

A shell is just another process, no different from any other process, except that this particular process waits for you to type a command, then it executes the typed command as a new process.

It should now become obvious why there isn't any actual "cd" command. Say there was one. So, you typed the "cd" command, and the shell executes the "cd" command as a new process.

The new process changes its current directory, and exits.

So, what did you accomplish? Absolutely nothing. The shell's current directory has not changed. All that the "cd" process would do, in this hypothetical case, is change its own current directory, and nothing else. Then it terminates, and everything's back to the way it was before.

That's why "cd" is a built-in command. This command is one of several commands that's executed by the shell directly, and this command changes the shell's current directory. So, all future processes started from this shell will now have a new current directory.

The system call that changes the process's current directory is chdir(2). C, Perl, Python, and pretty much every other programming language has some function somewhere called chdir, or something similar, that executes the system call that changes the process's current directory.

alk
  • 69,737
  • 10
  • 105
  • 255
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148