I am trying to change the value of a position of an array inside a struct that is allocated in shared memory I have this struct:
typedef struct Paths {
int *path;
int totalDistance;
int quantity;
}Path;
And i have this algorithm:
void runAlgorithm(int** distances,int nCities, int executionTime, int nProcesses){
int size = nCities+2 * sizeof(int);
int protection = PROT_READ | PROT_WRITE;
int visibility = MAP_ANONYMOUS | MAP_SHARED;
PtPath shmem = (PtPath)mmap(NULL, size, protection, visibility, 0, 0);
*shmem = createPath(nCities);
randomPath(shmem);
setPathTotalDistance(shmem, distances);
sem_unlink("job_ready");
sem_unlink("job_done");
sem_t *job_ready = sem_open("job_ready", O_CREAT, 0644, 0);
sem_t *job_done = sem_open("job_done", O_CREAT, 0644, 0);
int *pids = (int*)calloc(nProcesses, sizeof(int));
Path path, shortestPath;
//Workers Processes
for(int i = 0 ; i < nProcesses ; i++){
pids[i] = fork();
if(pids[i] == 0){
shortestPath = createPath(nCities);
randomPath(&shortestPath); //inicializa caminho aleatorio
setPathTotalDistance(&shortestPath, distances); //problema aqui
while(1){
sem_wait(job_ready);
mutation(&shortestPath, distances);
if(shortestPath.totalDistance < shmem->totalDistance){
printPath(shmem);
printPath(&shortestPath);
copyPath(&shortestPath, shmem);
}
sem_post(job_done);
}
exit(0);
}
}
//Parent Process
int elapsed, terminate = 1;
time_t start = time(NULL), end;
printf("Elapsed time: \n");
while(terminate){
end = time(NULL);
elapsed = difftime(end,start);
printElapsedTime(elapsed);
if(elapsed >= executionTime)
terminate = 0;
else{
sem_post(job_ready);
sem_wait(job_done);
}
}
printPath(shmem);
sem_close(job_ready);
sem_close(job_done);
// Kill worker processes
for (int i=0; i<nProcesses; i++) {
printf("Killing %d\n", pids[i]);
kill(pids[i], SIGKILL);
}
}
This is the code of createPath:
Path createPath(int quantity){
Path newPath;
if(quantity < 0)
quantity = 0;
newPath.path = (int*)calloc(quantity, sizeof(int));
newPath.quantity = quantity;
newPath.totalDistance = 0;
return newPath;
}
And this is the copyPath code:
void copyPath(PtPath from, PtPath to){
for(int i = 0 ; i < from->quantity ; i++){
//printf("posI: %d\n",to->path[i]);
to->path[i] = from->path[i];
}
to->totalDistance = from->totalDistance;
to->quantity = from->quantity;
}
So my problem is i'm trying to copy the shortestPath to the shared memory and it copies nothing, but it does copy the totalDistance What am i doing wrong and where?