【问题标题】:"cd" command does not work in my custom shell [duplicate]“cd”命令在我的自定义 shell 中不起作用 [重复]
【发布时间】:2020-03-29 16:17:21
【问题描述】:

cd 命令有问题。其他一切似乎都有效,例如编译和运行程序,以及ls。我运行lsls -1 并且工作得很好。当我运行 cdcd Desktop 时,没有任何反应。

我正在创建一个 fork,然后执行一个进程。我退出 exit 或按 CTRL+D

代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

#define SIZE 255

void printPrompt(){

    printf("\nuser@shell > ");   //print prompt

}

void readPrompt(char string[],int *check){   //read prompt line from user

    if( (scanf(" %[^\n]",string)==EOF) ){
        //printf("\nTEST\n");
        *check=0;
    }
    printf("\n");
}

void RunSimple(char line[]){    //creating a fork and running a program with exe fuction. 

    char **args=malloc(8 * sizeof(char *));
    char *parsed;
    int i=0,pid;

    parsed = strtok(line," ");

    while (parsed != NULL) {
        args[i] = parsed;
        i++;

        parsed = strtok(NULL," ");
    }

    pid = fork();

    if(pid == 0){
        execvp (args[0],args);
    }

    waitpid(pid,NULL,0);
}

int main(int argc, char **argv){

    char line[SIZE];
    int check=1;

    while(1){

        printPrompt();
        readPrompt(line,&check);

        if( (!strcmp(line,"exit")) || (check==0) ){
            break;
        }

        RunSimple(line);
    }
}

谢谢。

【问题讨论】:

标签: c linux shell ubuntu


【解决方案1】:

cd 必须作为内置实现,因为当前工作目录是进程的属性。因此,cd 命令必须更改 shell 的状态,这是子进程无法做到的。还有其他一些事情,比如环境变量的处理,必须这样处理。

【讨论】:

  • 你能再解释一下吗?谢谢。
  • @SteliosSpector,略微扩展。另请参阅 jww 指出的重复项。如果这还不够,您可以再问一个问题,用这些指针解释您不理解的地方。
猜你喜欢
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 2016-02-06
相关资源
最近更新 更多