【发布时间】:2020-11-05 01:46:37
【问题描述】:
我目前正在创建自己的 linux shell。我可以在我的目录中“ls”等等。然而, 当我尝试“cd”进入子目录时,它实际上从未改变。代码运行但实际上并没有更改我的目录。 在我的 linux 文件系统上,我有目录
/
home
testing
foo.txt
testingForShell
bar.txt
为了获取当前目录,我使用...
void execute(string command, char *
const * args, char * path) {
int pid = -5;
int child = -5;
int status;
pid = fork();
if (pid == 0) {
if (command.substr(command.length() - 2).compare("cd") == 0) {
const char * currentPath;
if ((currentPath = getenv("HOME")) == NULL) {
currentPath = getpwuid(getuid()) -> pw_dir;
}
cout << (string(currentPath) + "/" + string(args[1])).c_str() << endl;
int dir = chdir((string(currentPath) + "/" + string(args[1])).c_str());
} else {
char * pathArgs = strtok(path, ":");
while (pathArgs != NULL) {
try {
execv((string(pathArgs) + "/" + command).c_str(), args);
} catch (...) {
}
pathArgs = strtok(NULL, ":");
}
}
exit(0);
} else {
waitpid(-1, & status, 0);
}
}
子进程中的第一个 if 是他们是否要“cd”到一个目录中。 else 用于其他命令,例如“ls”。
cout 打印出/home/testing/testingForShell 但当我再次调用“ls”时,它从未进入目录以显示 bar.txt。如果我提供了足够的信息,请告诉我。我非常有信心我使用 chdir 错误,但情况可能并非如此。注意:我正在尝试更改正在运行的脚本中的目录,而不是我启动脚本的实际 linux 终端。
【问题讨论】: