Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I created my own shell, I am not able to execute cd command which I am able to do in the Linux shell. Why is that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
591 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's probably because the cd command has to be built into the shell, not something external and executed. If an external command changed directory, it has no effect on the parent shell. (Even though there is usually a command /bin/cd or /usr/bin/cd on Linux and macOS systems, executing it changes the directory for that process, but has no effect on the process that invoked it.)


I do not understand the line "If the external command changed directory, it has no effect on the parent shell".

Normally, when a shell executes a command, it does fork() and the child process uses exec() to execute the command entered by the user. For example, if the entered command is 'ls /', the shell arranges to execute /bin/ls with two arguments, ls and /. However, if the command selected executes the chdir() system call, that affects the child process, but does not affect the parent shell. So, the shell has to handle the cd command itself, not via fork() and exec().

Note that in DOS, a .BAT file can do cd and it affects the cmd.exe process. This does not happen in Unix — a child process cannot affect the current directory of the parent process.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...