When I use chdir() to change the current directory, the program will not change when the program is shut down. So How can I apply chdir() to Shell after using chdir() and programs have been terminated?
-
**Why do you ask**? Please **edit the question** to improve it and motivate it. – Basile Starynkevitch Nov 01 '16 at 09:09
-
You can think of modifying PWD environment variable (depending on your OS). But I've not tested it. – LotoLo Nov 01 '16 at 09:12
-
1@LotoLo: changing `PWD` won't affect the current directory of parent process (i.e. the shell's process) – Basile Starynkevitch Nov 01 '16 at 09:17
-
Related: http://unix.stackexchange.com/q/141313/10947 (1st hit on gxxgle for "*chdir does not work in C*", BTW!) – alk Nov 01 '16 at 11:14
-
1Possible duplicate of [How do I set the working directory of the parent process](http://stackoverflow.com/questions/2375003/how-do-i-set-the-working-directory-of-the-parent-process) – Mark Plotnick Nov 01 '16 at 11:57
1 Answers
You cannot do that (changing your parent shell directory from inside a C program). The current directory is an attribute of every process, and your shell runs in a different process than your program (so the shell process and your program's process have each their own current directory).
Read Advanced Linux Programming. It has several chapters related to your issue.
Perhaps you might add some shell function (e.g. into your ~/.bashrc
...) which perhaps could use eval
to run your C program (which would output some cd
command, that the eval
or source
builtin of your shell would handle within the same shell process); BTW ssh-agent might be inspirational. Actually I don't recommend this route if you are a newbie.
PS. You really should motivate your question and give a lot more context; it smells badly like an XY problem.

- 223,805
- 18
- 296
- 547
-
-
1@Ashish: I don't understand what you mean (and how it is related to the OP's question), and that does not change the fact that every process has its own current directory. – Basile Starynkevitch Nov 01 '16 at 09:14