dimi67
asked on
matrix addition using shared memory
I want to add 2 matrices using shared memory and parallel processes, in linux, but my code doesnt run correctly .
Where is the problem?
Where is the problem?
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <stdlib.h>
int main ()
{
int idA,idB,idC, child_id;
int *A,*B, *C;//the 3 arrays
int* child_memory;
int *pA, *pB, *pC;
const int size = 4096;
int i;
//allocate shared memory for an array of 5 integers
idA = shmget(IPC_PRIVATE, 5*sizeof(int), S_IRUSR | S_IWUSR);
idB = shmget(IPC_PRIVATE, 5*sizeof(int), S_IRUSR | S_IWUSR);
idC = shmget(IPC_PRIVATE, 5*sizeof(int), S_IRUSR | S_IWUSR);
//attach shared memory to parent
A = (int *) shmat(idA, NULL, 0);
B = (int *) shmat(idB, NULL, 0);
C = (int *) shmat(idC, NULL, 0);
for(i=0; i<5; i++){
A[i]=1;
B[i]=2;
C[i]=0;
}
for (i=0; i<5; i++){
printf("A[%d]=%d B[%d]=%d C[%d]=%d\n",i,A[i],i,B[i],i,C[i]);
}
printf("\n");
for(i=0;i<5; i++){
child_id=fork();
if (child_id==0){
A = (int*) shmat(idA, NULL, 0);
B = (int*) shmat(idB, NULL, 0);
C = (int*) shmat(idC, NULL, 0);
C[i] = A[i] + B[i];
}
else if (child_id>0){
wait(0);
}
else {perror("fork");exit(1);}
}
printf("C[%d] = %d ", i,C[i]);
shmdt(A);shmdt(B);shmdt(C);
shmctl(idA, IPC_RMID, NULL);
shmctl(idB, IPC_RMID, NULL);
shmctl(idC, IPC_RMID, NULL);
return 0;
}
Could you elaborate a bit on how it doesn't run correctly ? What do you observe ? What did you expect instead ?
ASKER
.if you run the code you will see that t values of array C don't change at all...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ok men, I fixed it with exit(0) at the end of the child...