I am creating a simple shell in c, and in order to recognize the "cd" command I have to implement chdir(). I know that it takes a char* as an argument, but how to I get it to execute the equivalent of "cd .."?
Asked
Active
Viewed 4,930 times
1
-
1What, did `chdir("..")` not work? – user2357112 Apr 05 '16 at 01:12
-
If I call it from a child process, will it not change in the parent process? – t_roper14 Apr 05 '16 at 01:17
-
Why are you doing it in a child process? – user2357112 Apr 05 '16 at 01:23
-
Because the user is able to input multiple commands at once, which I then use fork to run each command in a child process using execvp(), but in this case I have to use chdir(). So used an if-statement to check if the command is "cd" or not. I'm assuming I wont be able to do it in a child process and will have to check if it is "cd" before I fork(). @user2357112 – t_roper14 Apr 05 '16 at 01:28
-
I fixed it thank you! @user2357112 – t_roper14 Apr 05 '16 at 01:36
-
If you put `cd` into a child process, how are you going to implement `exit`? Note that `cd` operations such as `cd ~` and `cd ~user` require processing by the shell, whereas most alternatives do not. See also [`chdir()` to home directory](https://stackoverflow.com/questions/9493234/chdir-to-home-directory) – Jonathan Leffler Apr 05 '16 at 04:59
-
1@user2357112 `chdir("..")` is not the correct way to implement `cd ..`, it will do the wrong thing when symlinks are involved. See the `-P` and `-L` options. – o11c Apr 05 '16 at 05:14
-
@o11c: How is its behavior wrong? It sounds like we just have different expectations. – user2357112 Apr 05 '16 at 05:38
-
@user2357112 My "expectations" are defined by POSIX: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cd.html – o11c Apr 05 '16 at 14:25
-
@o11c: Hm. Looks like you're right. – user2357112 Apr 05 '16 at 15:08
2 Answers
1
Use chdir("..");
. It will allow you to move to the previous directory like cd ..

Federica Benacquista
- 835
- 11
- 25

aayush maurya
- 11
- 1
0
cd is a built-in command in the shell; it can't be implemented as a separate program. If you want to have a program change your shell's current directory for you, you'll need to do it indirectly. You may wish to have a look at the chdir
function in <unistd.h>
. This changes the working directory of the current process. Also refer to this link for reference purposes.

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278

msc
- 33,420
- 29
- 119
- 214