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

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

linux - Why doesn't the cd command work in my shell program?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...