poppinMartinellis
poppinMartinellis

Reputation: 89

The cd command in C and use of chdir()

I'm tasked with programming the linux cd command in C. I thought this would be fairly trivial by using the chdir() method, but my directories aren't changing. What's interesting is that the return status of chdir() is 0, not -1, meaning chdir() has not failed. Here are the two cases where I'm using chdir():

1.

    char *dir = getenv("HOME");   // Here dir equals the home environment.
    int ret = chdir(dir);

    printf("chdir returned %d.\n", ret);

ret returns 1.

2.

    int ret = chdir(dir);   // Here dir equals the user's input.

    printf("chdir returned %d.\n", ret);

ret returns 1 if the directory exists in my path.

Am I using chdir() wrong? I can't seem to find an answer for this anywhere. Any help would be much appreciated.

Upvotes: 2

Views: 10630

Answers (1)

Daniel Jour
Daniel Jour

Reputation: 16156

chdir() changes the working directory of the calling process only.

So when you have code like ...

int main() {
  // 1
  chdir("/"); // error handling omitted for clarity
  // 2
}

... and compile that to a program example and then run it in a shell:

$ pwd # 3
/home/sweet
$ ./example # 4
$ pwd # 5
/home/sweet

Then you have two processes in play,

  1. the shell, which is where you entered pwd and ./example

  2. ./example, the process launched (by the shell) with your compile program.

chdir() is part of your compiled program, not the shell, thus it affects only the process with your program, not the shell.

So, at // 1 the working directory of your program (in above example run) is /home/sweet, but at // 2 it is / as specified in the chdir() call above. This doesn't affect the shell and the output of pwd # 5 though!

Upvotes: 7

Related Questions