在C中查找已知名称的文件地址

Finding the adress of file knowing the name in C

我正在为一个项目在 C/Ubuntu 中编写自己的 shell,但是在使用 chdir() 实现 cd 时我遇到了一些困难。 chdir() 需要路径名,但由于用户将写入(让我们假设)cd DesktopDesktop 不是路径名,因此程序将失败。

这是我的那部分代码:

child = fork();
if (child == 0) {
    if (!strcmp(args[0], "ls")) {
        execv("/bin/ls", args);
    }
    if (!strcmp(args[0] , "cd")) {
        chdir(args[1]);
    }  
    perror("Error");
    exit(1);  //Failure
} else {
    do {
       waitpid(child, &status, WUNTRACED);
} while(!WIFEXITED(status) && !WIFSIGNALED(status)); 

所以我认为问题是 args[1] 得到的是 "Desktop" 之类的东西而不是地址,所以 chdir 失败了。我在终端测试了它,除了 cd 之外的所有其他命令都有效。我的问题是如何让这个 chdir 工作?换句话说,我怎样才能将 args[1] 的路径提供给 chdir

让我这样说吧。当我将 cd Desktop 写入终端时,它起作用了。当我将 cd Desktop 写入自己的 shell 时,它会尝试执行 chdir("Desktop") 但失败了。

你使用exec到运行的ls命令,我怀疑你fork()选择执行哪个命令之前的过程:chdir(args[1])是在子进程中执行,子进程改变当前目录,然后退出。每个进程都有自己的当前目录。父级 (shell) 处理当前目录不受其子级更改的影响,它保留其当前目录。

大多数命令应该在 shell 进程中执行而不分叉,只有外部命令应该在分叉到子进程后执行。

这是您的代码的修改版本:

/* frist execute local commands in the shell process. */
if (!strcmp(args[0], "cd")) {
    if (!args[1]) {
        fprintf(stderr, "cd: missing argument\n");
    } else
    if (chdir(args[1])) {
        perror("chdir");
    }
} else
if (!strcmp(args[0], "exit")) {
    int status = args[1] ? atoi(argv[1]) : 0;
    exit(status);
} else {
    /* otherwise, fork and attempt to execute an external command */
    child = fork();
    if (child == 0) {
        if (!strcmp(args[0], "ls")) {
            execv("/bin/ls", args);
        }
        /* if exec failed, the child process is still running */
        perror("exec");
        exit(1);  //Failure
    } else {
        do {
           waitpid(child, &status, WUNTRACED);
    } while(!WIFEXITED(status) && !WIFSIGNALED(status));
}