Using chdir() to change directory from Terminal

2020-04-14 11:38发布

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.

标签: c shell chdir
2条回答
爷的心禁止访问
2楼-- · 2020-04-14 12:28

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.

查看更多
欢心
3楼-- · 2020-04-14 12:38

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
}
查看更多
登录 后发表回答