I am reading from the user the size of an arr. I create the arr[row][col] and fill it with random integers. Then i want to send each row from the parent process to the child so i create a new arr2 to store every time the current row in it. I read the arr2 to child process and calculating the sum of the row. At the end i want to send the sum to parent process and print it. I do this in a for(i=0;i<row;i++). The problem is that the child process only takes the first row every time.
#include <sys/types.h>
#include<stdio.h>
#include <unistd.h>
#include<time.h>
#include<stdlib.h>
int main(){
int gram, steiles;
printf("Dwse mou tis grammes tou pinaka\n");
scanf("%d", &gram);
printf("Dwse mou tis steiles tou pinaka\n");
scanf("%d", &steiles);
int arr[gram][steiles];
int arr2[gram];
srand(time(NULL));
for (int i = 0; i < gram; i++) {
for (int j = 0; j < steiles; j++) {
arr[i][j] = rand() % 20 + 1;
}
}
for (int i = 0; i < gram; i++) {
for (int j = 0; j < steiles; j++) {
printf("%d", arr[i][j]);
printf("\t");
}
printf("\n");
}
pid_t pid;
int fd[2], fd1[2], sum=0;
if (pipe(fd) == -1) {
return 2;
}
if (pipe(fd1) == -1) {
return 3;
}
for (int i = 0; i < gram; i++) {
pid = fork();
if (pid<0) {
return 1;
}
if (pid>0){
for (int j = 0; j < steiles; j++) {
arr2[j]=arr[i][j];
}
close(fd[0]);
write(fd[1], arr2, sizeof(int)*steiles);
close(fd[1]);
close(fd1[1]);
read(fd1[0], &sum, sizeof(int));
close(fd1[0]);
printf("the sum of the row is: %d", sum);
}else{
wait(NULL);
close(fd[1]);
read(fd[0], arr2, sizeof(int)* steiles);
close(fd[0]);
for (int k = 0; k < steiles; k++) {
// printf("%d\t", arr2[k]);
sum+=arr2[k];
}
close(fd1[0]);
write(fd1[1], &sum, sizeof(int));
close(fd1[1]);
}
}
}