如何在 C 中处理管道中的 n 个命令?

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

所以我有一个任务,我必须处理管道中的 n 个命令。这些命令基于 Linux。如果我的理解是正确的,我知道我必须创建一个 for 循环,连续 forks() 主进程的子进程,并执行这些子进程,然后通过管道连接它们。这是到目前为止我的代码。

void  main(void)
{
    char **cmds[3];
    char *c1[] = { "ls", "-l", "/etc", 0 };
    char *c2[] = { "head", "-n", "10", 0 };
    char *c3[] = { "tail", "-n", "5", 0 };
    cmds[0] = (char **)c1;
    cmds[1] = (char **)c2;
    cmds[2] = (char **)c3; 
    
    int pid, status;
    pid = fork();
    
    if(pid == 0){//child proccess
        int fd[2];
        int infd;
        int i;
        for(i = 0; i < 2; i++){
            pipe(fd);
            int ppid;
            ppid = fork();
            
            if(ppid > 0){
                dup2(fd[1], 1);
                close(fd[0]);
                //executes the nth command
                execvp(*(cmds+i)[0], *(cmds+i));
            }else if(ppid == 0){
                dup2(fd[0], 0);
                close(fd[1]);
                //executes the n+1th command
                execvp(*(cmds+i+1)[0], *(cmds+i+1));
            }
        }
    }else if (pid > 0){//parents proccess
        while((pid = wait(&status)) != -1);
        
    }
}

就目前的程序而言,我只能通过管道传输第一个和第二个命令,但由于某种原因,第三个命令完全未被检测到。我该如何解决这个问题?

c linux fork pipeline
1个回答
0
投票

我认为循环的终止条件应该是i<=2 or i<3 if you have to process three indexes of loop.

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