How to make an array sum using shared memory?

0

I need help to perform a sum of arrays using shared memory.

#define LINHAS 3
#define COLUNAS 3
#define PULAR_LINHA printf("\n")

int main(int argc, char *argv[])
{

  int linha, coluna;    //indices
  int pid, id;
  int matriz1[][COLUNAS] = { {1,2,3}, {4,5,6}, {7,8,9} };
  int matriz2[][COLUNAS] = { {3,5,3}, {4,5,6}, {7,8,9} };
  int segmento, status;
  segmento = shmget(IPC_PRIVATE, sizeof(int)*18, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
  int *matrizSolucao = (int*)shmat(segmento, NULL, 0);
  id = fork();

  if (id == 0)  // Processo filho
  {
        for(linha = 0; linha < LINHAS; linha++)
        {
            for(coluna = 0; coluna < COLUNAS; coluna++)
            printf("%d\t", *matrizSolucao);
            printf("\n");
        }
  }
  else          // Processo pai
  {
        pid = wait(&status);
        for(linha = 0; linha < LINHAS; linha++)
        {
            for(coluna = 0; coluna < COLUNAS; coluna++)
            *matrizSolucao = matriz1[linha][coluna] + matriz2[linha][coluna];
        }
  }
  //Libera a mmoria compartilhada do processo
  shmdt(matrizSolucao);
  //Libera a memoria compartilhada
  shmctl(segmento, IPC_RMID, 0);
  return EXIT_SUCCESS;
}

With this code the matrix actually appears, but with all its values zeroed, can anyone help? Thank you.

    
asked by anonymous 01.04.2015 / 03:07

2 answers

1

In your code, the child process prints; the parent process calculates. The parent process waits for the child to finish before calculating, so the child process prints zeros.

Change the parent and child process codes.

    
01.04.2015 / 10:48
0

From what I saw in the code you do:

*matrizSolucao = matriz1[linha][coluna] + matriz2[linha][coluna]

I think you are always putting the sum in the first position, or any sum you make will be going to the first position and not going to the right position.

And when you do:

for(linha = 0; linha < LINHAS; linha++)
{
    for(coluna = 0; coluna < COLUNAS; coluna++)
        printf("%d\t", *matrizSolucao);
        printf("\n");
}

You are printing the first position again every time.

And about the zero values is what same PMD said up there about the son being inverted with the father.

    
18.05.2015 / 04:59