Lev Kolomazov
Lev Kolomazov

Reputation: 87

C - using different pipe ends in different processes

I've been searching and reading manuals, but still can't get the pipe mechanism. I'm making a program, which should do the following:

  1. Parent process creates pipe, two child proccesses and waits.

    1. First child generates pairs of random numbers and passes them with space between to the second process via pipe. It goes on till gets signal from parent.
    2. Second child redirects it input so it is the output of the first child and redirects output to the out.txt file. Then it executes already compiled program, calculating GCD of numbers from (1);
  2. Parent closes pipe and kills child.

So I got this C code (I reduced it so the post can fit the rules):

const int PIPE_READEND=0;
const int PIPE_WRITEEND=1;

        (...)
if (child1 == 0) {
        //Child1 code here
        close(fd[1]);

        struct sigaction sa;
        sa.sa_handler = sigHandler;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = 0;
        if (sigaction(SIGUSR1,&sa,NULL) == -1){ //Handling SIGUSR1 signal
            perror("Signal handling unexpected error");
            exit(errno);
        }
        int a,b;
        srand(time(&t));
        if (dup2(fd[PIPE_READEND],1) < 0){ //Redirecting stdout to the pipe fd.
            perror("In Child1 Redirecting stdout to pipe error");
            exit(errno);
        } 
        close(fd[0]);
        while(1){
            a = rand();
            b = rand();
            printf("%d %d\n", a, b);
            sleep(1);
        }


       (...)
if ((child2 = fork()) < 0){
        perror("Fork error in Child2 process");
        exit(errno);
    } else if (child2 == 0){
        //Child2 code here
        close(fd[PIPE_READEND]);
        FILE *outfile = fopen("out.txt","w");
        dup2(fd[PIPE_WRITEEND],0); 
        dup2(outfile,1); 
        close(fd[PIPE_WRITEEND]);
        execl("c1/main","main",(char *)NULL);   

The problem is, after executing it, out.txt stays empty. I'm disappointed about the pipe array indices, which one is used for what.

Upvotes: 1

Views: 499

Answers (2)

Ford O.
Ford O.

Reputation: 1498

You write and read from wrong indexes of pipe. You need to change them:

This redirects stdout to pipe input.

   close(fd[0]);
   dup2(fd[1], STDOUT_FILENO);

This redirects pipe output to stdin.

   close(fd[1]);
   dup2(fd[0], STDIN_FILENO);

Also dup2 takes integer, not pointer, so you should do:

   f = fopen("out.txt", "w");
   dup2(fileno(f), STDOUT_FILENO);

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182865

    FILE *outfile = fopen("out.txt","w");
    dup2(fd[PIPE_WRITEEND],0); 
    dup2(outfile,1); 

This makes no sense. The dup2 function doesn't take a FILE * as a parameter. Use open, not fopen.

Upvotes: 1

Related Questions