| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 
 | #include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<assert.h>
#include<unistd.h>
#include<string.h>
 
int main(int argc, char* argv[])
{
    int pipefd[2] ,pipefd2[2];
    int cpid,cpid2;
    char buf,buf2;
    assert(argc==3);
    if(pipe(pipefd)==-1)
    {
        perror("pipe");
        exit(EXIT_FAILURE);
    }
    cpid=fork();
    if(cpid==-1)
    {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    if(cpid==0)
    {
        /* child reads from pipe */
        close(pipefd[1]); /*close unused write end */
        while(read(pipefd[0],&buf,1)>0)
        {
            write(STDOUT_FILENO,&buf,1);
            write(STDOUT_FILENO, "\n", 1);
        }
        close(pipefd[0]);
        exit(EXIT_SUCCESS);
    }
    else
    {
        /*parent writes argv[1] to pipe */
        close(pipefd[0]);/*close unused read end */
        write(pipefd[1],argv[1],strlen(argv[1]));
        close(pipefd[1]); /* reader will see EOF */
//wait(NULL);  /*wait for child */
        if(pipe(pipefd2)==-1)
        {
            perror("pipe");
            exit(EXIT_FAILURE);
        }
        cpid2=fork();
        if(cpid2==-1)
        {
            perror("fork");
            exit(EXIT_FAILURE);
        }
        if(cpid2==0)
        {
            /* child2 reads from pipe */
            close(pipefd2[1]); /*close unused write end */
            while(read(pipefd2[0],&buf2,1)>0)
            {
                write(STDOUT_FILENO,&buf2,1);
                write(STDOUT_FILENO,"\n", 1);
            }
            close(pipefd2[0]);
            exit(EXIT_SUCCESS);
        }
        else
        {
            /*parent writes argv[1] to pipe */
            close(pipefd2[0]);/*close unused read end */
            write(pipefd2[1],argv[2],strlen(argv[2]));
            close(pipefd2[1]); /* reader will see EOF */
            wait(NULL);  /*wait for child */
            exit(EXIT_SUCCESS);
        }
    }
} | 
Partager