【问题标题】:Why does the pipe break out of the loop?为什么管道会脱离循环?
【发布时间】:2019-08-12 20:30:52
【问题描述】:

我正在为 c 开发一个 shell 程序,并试图弄清楚为什么它在提示用户响应后不断跳出循环。它正确运行命令,但是由于某种原因它中断了。我不知道为什么,我认为这与我做管道的方式有关。

这是我的示例,它应该运行管道命令,并要求用户一次又一次地继续运行该命令,直到用户输入“yes”以外的其他内容。可能是导致中断的 execvp 吗?我怎么能有它,所以它继续循环?使用分叉更新进行编辑。

#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>


int main()
{
    char str[3];
    do{
        char* leftSide[] = {"ls", NULL};
        char* rightSide[] = {"wc", NULL};

        pid_t id, id2;
        int pipe_fd[2];

        pipe(pipe_fd);
        id = fork();

        if(id == 0){
            dup2(pipe_fd[0],0);
            close(pipe_fd[1]);
            close(pipe_fd[0]);
            if(execvp(rightSide[0], rightSide) == -1){
                perror("error running pipe right command");
            }
        }
        else{
            id2 = fork();
            if(id2 == 0){
                dup2(pipe_fd[1],1);
                close(pipe_fd[1]);
                close(pipe_fd[0]);
                if(execvp(leftSide[0],leftSide) == -1){
                    perror("error running pipe left command");
                }
            }
            else{
                wait(NULL); 
                wait(NULL); 
            }
        }

        printf("Continue?");
        fgets(str, 3, stdin);
        str[3] = '\0';
    }while(strcmp(str, "yes") == 0);

    return 0;
}

【问题讨论】:

    标签: c linux shell unix pipe


    【解决方案1】:

    您正在通过以下方式终止您的程序

        if(execvp(leftSide[0],leftSide) == -1){
    

    你必须fork() 两次;一次用于rightSide,一次用于leftSide

    【讨论】:

    • 我向父级添加了一个 fork 并让它等待两次,但它仍然退出。我写对了吗?我玩弄了等待,等待了一次,两次,甚至删除了两个等待。
    【解决方案2】:

    这里有两个问题:

    1. 正如@ensc 在他的回答中指出的那样,您的程序在您调用execvp 时终止。您必须创建两个孩子,父母将保留您的程序,要求用户提供更多输入,而孩子将执行 leftsiderightside

    2. 第二个问题是fgets

    根据手册页:

    fgets() 从流中最多读入一个小于 size 的字符并将它们存储到 s 指向的缓冲区中。在 EOF 或换行符后停止读取。如果读取了换行符,会将其存储到缓冲区中

    因此,用户输入的字符串将是"yes\n" 而不是"yes",而strcmp 将始终失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多