c - 下一个 shell 提示符后显示 Unix 命令输出

标签 c shell unix command

我正在为一个学校项目开发一个用 C 编写的 shell,尽管这个问题没有你想象的那么复杂。问题是,当我键入命令(例如 ls)时,输出将显示在整个 shell 循环开始处显示的下一个 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;
}

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

最佳答案

pid_t wait_pid(pid);是错误的,它没有调用wait_pid。调用函数时,不指定返回类型。相反,请尝试:

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

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

关于c - 下一个 shell 提示符后显示 Unix 命令输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26087637/

相关文章:

unix - 如何使用getopt在UNIX中制作多字符参数?

c - unix 网络编程书籍代码由于旧操作系统而存在错误,如何解决这个问题或从哪里获得新代码?

html - 通过终端命令使用浏览器自动重新加载 html 文件

c++ - 临界区数据的原子操作

c++ - 如何判断给定路径是目录还是文件? (C/C++)

mysql - shell脚本不执行

linux - Linux 中的快速、半准确排序

c - c中的基数转换

c - 将指向函数的指针作为参数传递给具有多个参数的其他函数

scala - 错误 : value is not a member of object using Scala on the shell