0

Program:

    #include<stdio.h>
    #include<unistd.h>
    int main()
    {   
        char s[100];
        printf("%s\n",getcwd(s,100));
        chdir("..");
        printf("%s\n",getcwd(s,100));
        return 0;
    }

Output:

    $ ./a.out 
    /home/guest
    /home
    $ 

The above program changes the working directory of a process. But, it doesn't change the working directory of current shell. Because when the program is executed in the shell, the shell follows fork on exec mechanism. So, it doesn't affect the current shell.

Is there any way to change the current working directory of the shell via these program like a built-in (cd, echo) command used by the shell?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
mohangraj
  • 9,842
  • 19
  • 59
  • 94

1 Answers1

1

Is there any way to change the current working directory of the shell via these program like buildin(cd,echo) command used by the shell.

You can't do that.

Allowing a child process to change the current directory, or any state for that matter, of the parent process would wreak havoc on the parent process.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Then how builtin commands are implemented? – mohangraj Oct 15 '15 at 04:35
  • 3
    @mrg, built-in commands are interpreted by the shell and the shell can change its own state. – R Sahu Oct 15 '15 at 04:36
  • 3
    @mrg That's why they're built-in. When you type `cd`, the shell calls `chdir()` itself, it doesn't run it as a program. – Barmar Oct 15 '15 at 04:43
  • @Barmar Bash is also a seperate program which is written in C. Then how it is possible there? So, we can't do this. Is it right? – mohangraj Oct 15 '15 at 07:39
  • @mrg Bash is changing its own directory, just like your program does. It's not changing the directory of its parent process. When it runs programs, those are child processes, they inherit the directory from the parent. – Barmar Oct 15 '15 at 13:57