There is a task: Write a program to calculate the sum of matrix elements. The matrix is entered from a file. The calculation of the sums of the elements of each row is performed in separate processes. To transfer data to the parent process, use the named pipe mechanism (FIFO).
I found this solution, however it does not meet all the requirements:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
using namespace std;
int main(){
int fd[2];
int i,j;
int p[2];
int arr[2][2];
int marr[2];
FILE *file = fopen("matrix","r");
if (!file)
printf("NO FILE");
for(i = 0; i < 2; i++){
for(j = 0; j < 2; j++){
fscanf(file, "%d", &arr[i][j]);
printf("%d ", arr[i][j]);
}
printf("\n");
}
if(pipe(fd) < 0) {
printf("Pipe error!\n");
return 1;
}
int max=arr[0][0];
for (int i=0; i<2; i+=1){
p[i]=fork();
if(p[i]==0){
printf("%d subprocess\n", i);
max=arr[i][0];
for(j=0; j<2; j++){
if(max<arr[i][j]){
max=arr[i][j];
}
}
close(fd[0]);
printf("write to pipe: max=%d i=%d\n", max, i);
write(fd[1],&max,sizeof(int));
write(fd[1],&i,sizeof(int));
exit(0);
}
else{
}
}
close(fd[1]);
for(int k=0; k<2; k++){
read(fd[0],&max,sizeof(int));
read(fd[0],&i,sizeof(int));
printf("read from pipe: max=%d i=%d\n", max, i);
marr[i]=max;
}
printf("massiv max:\n");
for(i=0; i<2; i++){
printf("%d\n",marr[i]);
}
fclose(file);
return 0;
}
I tried to somehow change the relationship between the processes from pipe to fifo, but I can't check, because the code needs to be run on a linux virtual machine, and in QT the SIGSEGV error appears on the line
fscanf(file, "%d", &arr[i][j]);
, the reasons for which, as I understand it, can be very different.
The test file for this code will look like:
3 4
5 6
and it finds the maximum of each row. It won't be difficult for me to redo it for my task, the main problem is in fifo. I will be grateful for any hints.