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

Why is execvp() executing twice using fork()?

我正在实施 shell。

尝试更改目录以外的命令时,execvp() 运行,child 终止并创建新的 child。当我更改目录时,child 不会终止并创建一个新的 child。这是我的代码示例:

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);
    }
}

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

不过,如果我通过管道传输相同的信息(即 mybash < chdirtest),它会正确运行一次,然后终止 child,然后再次运行,除了原来的直接运行,然后终止最后的 child.

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

一个(原始)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);
    }
}