gpt4 book ai didi

c++ - 如何使用chdir更改目录?

转载 作者:行者123 更新时间:2023-12-03 07:22:31 25 4
gpt4 key购买 nike

我目前正在创建自己的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终端。

最佳答案

在 fork 的过程中更改工作目录可以正常工作……在该 fork 的过程中。
但这对 parent 没有任何帮助。因此,下一个执行的命令与以前在同一工作目录中。

关于c++ - 如何使用chdir更改目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64690067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com