Hi am new to this forum, I'd like to ask about how to make a shared memory in the following code using shmat(), shmget(), to path mata , matb , matc from parent to child process, because i tried using global variables but when the child process terminates it seems no update to the global variables
pls show me an example or sample code ...thnx inadvance
thnx
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
class MATRIX{
public:
int row;
int col;
int** MAT;
MATRIX(int row , int col);
~MATRIX();
};
MATRIX::MATRIX(int row_i , int col_i){
row=row_i;
col=col_i;
MAT=new int* [row];
int i;
for(i=0;i<=row-1;i++){
MAT[i]=new int [col];
}
}
MATRIX::~MATRIX (){
int i;
for(i=0;i<=row-1;i++){
delete MAT[i];
}
delete MAT ;
}
void init_mat(MATRIX& mat){
int temp=1;
for(int i =0 ; i<= mat.row -1 ;i++){
for(int j=0;j<=mat.col-1;j++){
mat.MAT[i][j]=temp++; //Any initialization
}
}
}
void print_mat(MATRIX& mat){
for(int i =0 ; i<= mat.row -1 ;i++){
for(int j=0;j<=mat.col-1;j++){
cout<<mat.MAT[i][j]<<" ";
}
cout<<endl;
}
}
void mul_col(MATRIX& mata ,MATRIX& matb,MATRIX& matc, int col){
int sum;
for (int j =0 ;j<= mata.row-1;j++){
sum=0;
for(int i= 0 ;i<=mata.col-1;i++){
sum=sum+mata.MAT[j][i]*matb.MAT[i][col];
}
matc.MAT[j][col]=sum;
}
}
MATRIX mata(3,3);
MATRIX matb(3,3);
MATRIX matc(3,3);
int main()
{
init_mat(mata);
init_mat(matb);
//print_mat(mata);
//print_mat(matb);
pid_t pid;
for (int k=0; k <= (matb.col-1);k++){
pid = fork();
if(pid == 0){
cout<<"am in mul place"<<endl;
mul_col(mata,matb,matc,k);
print_mat(matc);
cout<<k<<endl;
exit(0);
}
else if(pid > 0){
wait(NULL);
cout<<"i passed by the wait "<<endl;
}
else{
cout<<"Can't fork"<<endl;
}
if (pid == 0)
{
break;
}
}
if(pid > 0){
cout<<"am in the print area"<<endl;
print_mat(matc);
}
}