hey i want to increment a shared counter using shared memory and semaphores it is actually the code of richard stevens unp v2
Code:
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include <semaphore.h>
#define DEBUG 1
#define SHM_MODE (S_IRUSR,S_IWUSR,S_IRGRP,S_IROTH)
#define SHM_FLAGS (O_RDWR,O_CREAT,O_EXCL)
struct shmstruct
{
int count;
};//the structure used to share information in the shared memory
sem_t* mutex;
int main(int argc,char** argv)
{
int fd,i,nloop;
pid_t pid;
struct shmstruct *ptr;
if(argc!=4)
{
fprintf(stderr,"usage: shmsem_read <arg1=shmname> <arg2=semname> <arg3=#loops>");
}
nloop=atoi(argv[3]);
fd=shm_open(argv[1],O_RDWR,SHM_MODE);
ptr=mmap(NULL,sizeof(struct shmstruct),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
close(fd);
mutex=sem_open(argv[2],1);
if(mutex==-1)
{
perror("sem_open");
}
pid=getpid();
for(i=0;i<nloop;i++)
{
sem_wait(mutex);
if(DEBUG)
{
fprintf(stdout,"i m here for the %dth time t\n",i);
}
fprintf(stdout,"PId %ld:%d",(long)pid,ptr->count++);
sem_post(mutex);
}
exit(0);
}
gdb says that i m getting segmentation error from the sem_wait function i can't sort out why