Darkmer
Darkmer

Reputation: 47

Pipe not sending accurate information

I have started using pipe for a basic exercise. From processes A and B we get 2 random numbers. Process C does the sum of these 2 numbers and it prints it. The problem is that I don't get the correct values from reading. The values that enter in the pipe are not the ones that exit.

What is the problem here?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


int main(){

    int ac[2],bc[2];
    int f,g;
    if(pipe(ac)<0 || pipe(bc)<0){
        perror("Pipe error");
        exit(1);
    }

    f=fork();

    if(f<0){
        perror("Error fork1");
        exit(2);
    }
    if(f==0){
        g=fork();
        if(g<0){
            perror("Error fork2");
            exit(3);
    }
    if(g==0){
            printf("We are in  A \n");
            int variab=rand()%11+10;
            printf("Here we found the number %d\n",variab);
            write(ac[1],&variab,sizeof(int));
    }   
    else{
            wait(0);
            printf("We are in B\n");
            int variab2=rand()%6+5;
            printf("Here we found the number %d\n",variab2);
            write(bc[1],&variab2,sizeof(int));
    }
    }
    else{
        wait(0);
        printf("We are in C\n");
        int suma;
        int s1=read(ac[0],&s1,sizeof(int));
        printf("S1=%d\n",s1);
        int s2=read(bc[0],&s2,sizeof(int));
        printf("S2=%d\n",s2);
        suma=s1+s2;
        printf("Sum is %d\n",suma);
    }
    close(ac[0]);
    close(ac[1]);
    close(bc[0]);
    close(bc[1]);
    return 0;
}

Upvotes: 0

Views: 58

Answers (1)

user6365161
user6365161

Reputation:

The problem is with the lines

int s1=read(ac[0],&s1,sizeof(int));
...
int s2=read(bc[0],&s2,sizeof(int));

You are overwriting the value you want to get with the amount of bytes received by the read operation.

Make sure not to assign a new value to s1 and s2 by breaking up the line

int s1;
read(ac[0],&s1,sizeof(int));

(and similarly with s2) and it will work.

Upvotes: 2

Related Questions