Using chdir() to change directory from Terminal

烂漫一生 提交于 2019-12-20 02:55:05

问题


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.


回答1:


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.




回答2:


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
}


来源:https://stackoverflow.com/questions/27883841/using-chdir-to-change-directory-from-terminal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!