I am working on some code which uses the pthread and semaphore libraries. Here is my code but it dose not work and I think its because of sem_init function. I am new in C and really I don't know how to use sem_init, sem_open, sem_wait and sem_post. can someone give me some advice??
#include <sys/mman.h>
#include <math.h>
#include <wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <unistd.h>
#include<fcntl.h>
sem_t sem1,sem2;
float Calculate(int a,int b)
{
float d = ((a *a) + (b*b))/2;
return d;
}
int main()
{
int q;
int i,j,x;
float *Maddress, m, sum;
Maddress=mmap(NULL,sizeof(float),PROT_READ|PROT_WRITE,MAP_SHARED,-1,0);
sem_init(&sem2,0,1);
sem_init(&sem1,0,0);
sem_open("sem2",O_CREAT);
sem_open("sem1",O_CREAT);
if((q = sem_init(&sem1,1,0))!=0)
printf("error in create\n");
for(i=1;i<=10;i++)
{
j=fork();
if(j==0)
{
printf("The child %d is executing\n",i);
m=Calculate(i-1,i);
printf("child %d calculated value: %f\n",i,m);
sem_wait(&sem2);
Maddress=&m;
sem_post(&sem1);
exit(EXIT_SUCCESS);
}
}
for(j=1;j<=10;j++)
{
wait(&x);
if(WIFEXITED(x))
{
sem_wait(&sem1);
sum=sum+ (*Maddress);
sem_post(&sem2);
}
}
printf("The final result is: %f \n",sum);
sem_close(&sem1);
sem_close(&sem2);
return 0;
}