c - 在 C 上使用 fork 进程失败 while 循环

标签 c while-loop fork

我正在尝试创建一个简单的 shell 接口(interface)程序,该程序将 shell 命令作为来自父进程的用户输入,并通过实际执行 shell 命令的 pip IPC 将简单的 shell 命令发送到子进程。即使在输入“quit”后,子 while 循环也会继续重复

int main() {
    char userInput[BUFFER_SIZE];

    int fpipe[2];
    pid_t pid;

    // INTRODUCTION TO PROGRAM
    printf("------- WELCOME TO THE FORKED PARENT -------\n");
    printf("------- YOU MAY QUIT AT ANY TIME BY TYPING 'quit' or 'q' -------\n");

    if (pipe(fpipe)== -1){
        printf("------- PIPE HAS FAILED -------\n");
        return 1;
    }

    pid = fork();

    if (pid < 0){
        printf("------- FORK HAS FAILED -------\n");
        return 1;
    }

    if (pid > 0){
        close(fpipe[0]);
        printf("\nosh> ");
        scanf("%s", userInput);

        while ((strcmp(userInput,"quit") != 0 && strcmp(userInput,"q") != 0)){
            printf("\nosh> ");
            write(fpipe[1], userInput, strlen(userInput)+1);
            scanf("%s", userInput);
        }
        close(fpipe[1]);
    }

    else{
        close(fpipe[1]);

        while(1){
            if (read(fpipe[0], userInput, BUFFER_SIZE) == -1){
                return 1;

            }
            if ((strcmp(userInput,"quit") != 0 && strcmp(userInput,"q") != 0)){
                system(userInput);
                printf("osh> ");
            }
            else{
                break;
            }
        }
        close(fpipe[0]);
    }
    return 0;
}

最佳答案

问题是当用户输入quit时,父级中的循环停止,它不会将其发送给子级。因此子进程停止循环的条件永远不会匹配。它不断从管道中读取数据,但由于处于 EOF,因此它不会返回任何内容,因此它会继续执行发送的最后一个命令。

最简单的解决方案是子进程在从管道中获取 EOF 时跳出循环,而不是寻找退出

        while(1){
            int n;
            n = read(fpipe[0], userInput, BUFFER_SIZE);
            if (n == -1) {
                return 1;
            }
            if (n == 0) {
                break;
            }
            system(userInput);
        }

关于c - 在 C 上使用 fork 进程失败 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60645997/

相关文章:

c - 为什么在这个 Makefile 中只处理了一个变量的文件列表的一部分?

php - While in while 只显示一行?

c++ if(cin>>input) 在 while 循环中不能正常工作

java - 我如何在java中 fork 一个外部进程

python - Python Multiprocessing 如何在 Windows 上实现?

c - 赋值从指针生成整数,无需强制转换

c - 这些 typedef 用法有什么区别?

c - 在 c 中读取名称值对的最佳方法

字符串的Python多重比较

c - fork 错误?怎么修?