2

I am using chdir() to change directory to the value passed as an argument to this function.

I understand that when I run my C program using gcc myCd.c and ./a.out .. this changes the directory to the parent directory "within" the C program (i.e. a child process is spawned for the a.out process, and the change of directory happens within that child process).

What I want to do is, change the directory at the terminal using this C program. I tried writing a shell script for the same, and then sourcing it, and running, that works, but I wanted to achieve this using C.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
ATP
  • 832
  • 1
  • 15
  • 29
  • can you explain what is sourcing the script? – antonpuz Jan 11 '15 at 08:18
  • at the terminal entering 'source scriptname' very similar '. scriptname' Note: 'source' is not available in every scripting language. Usually it can be found in csh and bash – user3629249 Jan 11 '15 at 10:57
  • @Anton.P, by sourcing the script I meant, running the script in one of the two ways: 1. `. myScript.sh` 2. `source myScript.sh` But as @user3629249 has pointed out, it is not available in every scripting language. So will have to think of yet another way out! – ATP Jan 11 '15 at 19:47

2 Answers2

3

What you are attempting to do can't be done. The current working directory is a per-process attribute.

If you run a program which changes its cwd, it does not affect any other processes, except for any children it might create after the chdir().

The correct way to change the terminal's working directory is to use the cd command which the shell executes on your behalf and remains within the same process. That is, cd is one of several commands that the shell does not fork(); this makes the cd command work as expected.

sourceing a shell file makes it run within the shell's process. However, if you were to run the script without source, you'd find there was the exact same problem as with a C program: the shell forks to create a process for the script to run, it runs and then exits, and then the shell continues, but without its cwd changed.

wallyk
  • 56,922
  • 16
  • 83
  • 148
1

this is the way to change the current working directory in C

this needs the unistd.h header file to be included

if( 0 != chdir( "pathToNewDirectory" ) )
{ // then chdir failed
    perror( "chdir failed" );
   // handle error
}
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
user3629249
  • 16,402
  • 1
  • 16
  • 17
  • Yes, this is exactly the same way I have written my C program. And as mentioned in the comments and answers referenced to this post, the C Program will be spawned as a separate process, and will not change the directory of the parent process (the terminal) – ATP Jan 11 '15 at 19:51