I have written a very basic shell in C. It reads the input, then runs it using system(lineCopy); (lineCopy being a copy of the input). All commands will run fine in it, other than cd. When I try to cd to a different directory, it simply stays in the current directory. If I try to cd to a directory that doesn't exist, it says, as it should sh: 1: cd: can't cd to /some_nonexistant_directory. When I try to cd to a directory that DOES exist, however, it reads that command, but then stays in the same directory. The variable in which I store the current PWD is continuesly updating, so it cannot be that. All other commands work perfectly. But why does cd not?
Asked
Active
Viewed 864 times
0
-
4`cd` needs to be [a shell built-in](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cd.html#tag_20_14_16). – Michael Homer Jul 26 '15 at 08:23
-
Related: http://unix.stackexchange.com/q/38808/38906 – cuonglm Jul 26 '15 at 08:47
-
@MichaelHomer Is there a way of fixing this? – Jul 26 '15 at 09:27
-
2The answer to your next question is "use the [chdir](http://pubs.opengroup.org/onlinepubs/009695399/functions/chdir.html) system call". – Mark Plotnick Jul 26 '15 at 12:33
-
1You didn't write a shell at all. You wrote a C program that [calls a shell](http://pubs.opengroup.org/onlinepubs/009695399/functions/system.html), separately, for every single line of input. – Wildcard Feb 24 '17 at 00:39
1 Answers
0
Try changing an environment variable - that will not work either. System inherits the environment and the current working directory. So each system call will inherit the current working directory from its parent.
Ed Heal
- 258
- 2
- 11
-
-
1You cannot - the child does not change the parent in this respect. Anway why write a shell when not going the hole hog – Ed Heal Jul 26 '15 at 09:34
-
… or try defining an alias (and using it on the next line). … or getting a `history` listing. … or putting a command into the background with `&` and then looking at it with `jobs` or waiting for it with `wait`. … or setting `umask`. … or typing `exit` or `logout`. – G-Man Says 'Reinstate Monica' Jul 26 '15 at 10:46