【问题标题】:How to use chdir to change a directory?如何使用 chdir 更改目录?
【发布时间】: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 终端。

【问题讨论】:

    标签: c++ fork pid


    【解决方案1】:

    在一个分叉的进程中更改工作目录可以正常工作......在那个分叉的进程中。

    但它对父母没有任何作用。所以下一个执行的命令和之前在同一个工作目录中。

    【讨论】:

    • 他可以在 fork 之前 chdir。不知道他为什么要为 cd 分叉。
    • @Matt:如果命令是cd,那么分叉毫无意义。孩子会怎么做? OP 想要chdir 而不是分叉,这意味着测试必须在父级中。
    猜你喜欢
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 2021-07-17
    相关资源
    最近更新 更多