为什么cd命令在我的shell程序中不起作用? [英] Why doesn't the cd command work in my shell program?
问题描述
当我创建自己的shell时,我无法执行在Linux shell中能够执行的cd命令.为什么会这样?
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?
推荐答案
这可能是因为cd
命令必须内置在shell中,而不是外部的并可以执行.如果外部命令更改了目录,则它对父外壳无效. (即使在Linux和macOS系统上通常使用命令/bin/cd
或/usr/bin/cd
,执行该命令也会更改该进程的目录,但对调用它的进程没有影响.)
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".
通常,当外壳程序执行命令时,它会执行fork()
并且子进程会使用exec()
执行用户输入的命令.例如,如果输入的命令是'ls /
',则shell安排执行带有两个参数ls
和/
的/bin/ls
.但是,如果选择的命令执行chdir()
系统调用,则该操作会影响子进程,但不会影响父shell.因此,shell必须自己处理cd
命令,而不是通过fork()
和exec()
.
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()
.
请注意,在DOS中,.BAT
文件可以执行cd
,并且会影响cmd.exe
进程.在Unix中不会发生这种情况-子进程不会影响父进程的当前目录.
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.
这篇关于为什么cd命令在我的shell程序中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!