为什么execvp()使用fork()执行两次?

Aar*_*ker 5 c linux bash fork

我正在实现一个shell.

尝试除更改目录以外的命令,execvp()运行时,子进程终止并创建一个新子进程.当我更改目录时,子节点不会终止并创建一个新子节点.以下是我的代码示例:

for(;;) {
    printf("bash: ");
    parse();
    ...
    pid_t pid = fork()
    if (pid == 0)
        if (!strcmp(line[0], "cd"))
            if (!line[1]) (void) chdir(getenv("HOME"));
            else (void) chdir(line[1]);
        else execvp(line[0], line);
    ...
    if (pid > 0) {
        while (pid == wait(NULL));
        printf("%d terminated.\n", pid);
    }
}
Run Code Online (Sandbox Code Playgroud)

cd ../; ls;运行正常,除了我必须Ctrl+D两次结束程序.

虽然,如果我管道相同的信息(即.mybash < chdirtest),它运行正确一次,终止孩子,再次运行,除了在原件直接,然后终止最后的孩子.

Jea*_*nès 5

cd 不应该通过子进程调用,shell本身应该更改其当前目录(这是内部命令的属性:修改shell本身的进程).

一个(primitve)shell应该看起来像:

for(;;) {
    printf("bash: ");
    parse();

    // realize internal commands (here "cd")
    if (!strcmp(line[0], "cd")) {
       if (!line[1]) (void) chdir(getenv("HOME"));
       else (void) chdir(line[1]);
       continue; // jump back to read another command
    }

    // realize external commands
    pid_t pid = fork()
    if (pid == 0) {
        execvp(line[0], line);
        exit(EXIT_FAILURE); // wrong exec
    }

    // synchro on child
    if (pid > 0) {
        while (pid == wait(NULL));
        printf("%d terminated.\n", pid);
    }
}
Run Code Online (Sandbox Code Playgroud)