【问题标题】:Unix command output being displayed after next shell prompt在下一个 shell 提示符后显示 Unix 命令输出
【发布时间】:2014-11-23 02:55:57
【问题描述】:

我正在为一个学校项目编写一个用 C 语言编写的 shell,尽管这个问题没有你想象的那么深入。问题是当我输入命令时,例如ls,输出显示在下一个shell> 提示符之后,该提示符显示在整个shell 循环的开头。外壳看起来像:

shell>ls 
shell>Debug  shell.c

我的代码:

int main(){

    char line[255];

    while (1){
            printf("shell>");
            fgets(line, 255, stdin);
            if (strcmp(line, "exit\n") == 0){
                break;
            }
            else{
                char* args[255];
                size_t n = 0;
                for (char* ptr = strtok(line, " \n"); ptr; ptr = strtok(NULL, " \n")){
                    if (n >= 255){
                        break;
                    }
                    args[n++] = ptr;
                }
                args[n++] = NULL;
                for (size_t i = 0; i != n; ++i){
                    //printf("Token %zu is '%s'.\n", i, args[i]);
                }
                int pid = fork();
                if (pid == 0){
                    //child process code
                    int flag = execvp(args[0], args);
                    if (flag < 0){
                        perror("execvp failed");
                    }
                }
                else{
                    //parent process code
                    pid_t wait_pid(pid);
                }
            }
    }
    return 0;
}

除了所有其他错误,是什么导致输出以这种方式显示?

【问题讨论】:

    标签: c shell unix command


    【解决方案1】:

    pid_t wait_pid(pid); 错误,它不会调用wait_pid。调用函数时,不指定返回type。相反,请尝试:

    pid_t result_pid = wait_pid(pid);
    // add error handling etc here, check man page for return value details
    

    由于您实际上并没有等待子进程,因此父进程会立即打印提示,为您提供所看到的输出。

    【讨论】:

      猜你喜欢
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      相关资源
      最近更新 更多