为什么管子会脱离环路?

问题描述 投票:0回答:2

我正在研究一个针对c的shell程序,并尝试弄清楚为什么它在提示用户响应后不断突破循环。它正确运行命令,但由于某种原因它突然出现。我无法弄清楚为什么,我认为它必须采取我正在做管道的方式。

这就是我的例子,它应该运行管道命令,并要求用户一次又一次地继续运行命令,直到用户输入“是”以外的其他内容。这可能是导致休息的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
2个回答
2
投票

你正在终止你的程序

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

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


1
投票

这里有两个问题:

  1. 正如@ensc指出的那样,在他的回答中,当你调用execvp时,你的程序会终止。你必须生两个孩子,父母会留下你的程序,要求用户提供更多的输入,而孩子们将执行leftsiderightside
  2. 第二个问题是fgets

根据手册页:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.