c - 多管道实现。不工作

标签 c shell pipe

我正在为我的 shell 实现多管道。代码的问题是它不会将管道中最后一个命令的输出打印到我的 STDOUT。有人可以帮忙吗? executePipedCommands 函数接受指向命令列表头部的指针

例如,我将 ls|more|grep 插入到我的命令列表中。

struct cmd_t {
int nargs, maxargs;     
char **args;        
struct cmd_t *next;
};
typedef struct cmd_t *Cmd;
 void executePipedCommands(Cmd command) {

    int numPipes = -1;
    Cmd temp = command;
    int status;
    int i = 0;
    pid_t pid;

    while(command!= NULL)
    {   
        numPipes ++;
        command = command->next;
    }
    printf("number of pipes : %d",numPipes);


    int pipefds[2*numPipes];

    for(i = 0; i < (numPipes); i++){
        if(pipe(pipefds + i*2) < 0) {
            perror("couldn't pipe");
            exit(EXIT_FAILURE);
        }
    }


    int j = 0;
    while(command) 
    {
        pid = fork();
        if(pid == 0) 
        {

            //if not last command
            if(command->next)
            {
                if(dup2(pipefds[j + 1], 1) < 0)
                {
                    perror("dup2");
                    exit(EXIT_FAILURE);
                }
            }

            //if not first command&& j!= 2*numPipes
            if(j != 0 )
            {
                if(dup2(pipefds[j-2], 0) < 0)
                {
                    perror(" dup2");///j-2 0 j+1 1
                    exit(EXIT_FAILURE);

                }
            }


            for(i = 0; i < 2*numPipes; i++)
            {
                    close(pipefds[i]);
            }

            if( execvp(*command->args, command->args) < 0 )
            {
                    perror(*command->args);
                    exit(EXIT_FAILURE);
            }
        }
        else if(pid < 0)
        {
            perror("error");
            exit(EXIT_FAILURE);
        }

        command = command->next;
        j+=2;
    }
    /**Parent closes the pipes and wait for children*/

    for(i = 0; i < 2 * numPipes; i++){
        close(pipefds[i]);
    }

    for(i = 0; i < numPipes + 1; i++)
        wait(&status);

}

最佳答案

您的代码从 command 开始逐步遍历链表,并在到达末尾时停止,以便计算所需的管道数量。不幸的是,您没有将列表重置回起点,因此您无法单步执行列表来执行命令,因为您已经位于末尾。

您可能想写:

int numPipes = -1;
Cmd temp = command;

while (temp != NULL)
{   
    numPipes++;
    temp = temp->next;
}
printf("number of pipes: %d\n", numPipes);

变量 temp 不被使用。或者你可以写:

int numPipes = -1;
Cmd temp = command;

while (command != NULL)
{   
    numPipes++;
    command = command->next;
}
printf("number of pipes: %d\n", numPipes);

command = temp;

关于c - 多管道实现。不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19107123/

相关文章:

C预处理器#if表达式

c - msgget() 和 ftok() 出错

c - 在linux上使用c保存bmp文件

linux - 在排除 'ps grep command' 的同时查找进程状态的 Shell 脚本

shell - SUS/POSIX shell 兼容的 '-nt' 测试替换

c - 如何在我的程序中使用终端命令的输出?

c - C语言中初始化变量的函数

Android 10 - netstat 执行无法正常工作

c - C shell 管系统

linux - 如何连接两个文件并将结果写回原始文件之一