首页 > 解决方案 > 如何使用 chdir 更改目录?

问题描述

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

标签: c++forkpid

解决方案


在分叉进程中更改工作目录将正常工作......在该分叉进程中。

但它对父母没有任何作用。因此,执行的下一个命令与之前位于同一工作目录中。


推荐阅读