I am beginner thread programmer. i have done some small program on thread creation locking and semaphore by using semaphore.h and pthread.h header files.I have got stuck in the following program. We have two C program which share a memory segment (we have used ftok,shmget,shmat shmdt shmctl). I want to create semaphore which can be accessed by the both the programs such that with the help of semaphore we can allow access of shared memory by exactly one process at any time. May any body give a simple program for that? I have written some program but it is not working as I want.
Program 1:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<semaphore.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<unistd.h>
#define SEGMENTSIZE sizeof(sem_t)
#define SEGMENTPERM 0666
void sharedmemory()
{
char *s;
int err,id;
key_t key=ftok("shm",45);
id=shmget(key, SEGMENTSIZE , SEGMENTPERM );
/* Attach the segment . */
s=shmat(id,(void*) 0, 0);
gets(s);
printf("Written data in memory");
err=shmctl(id, IPC_RMID , 0);
if(err==-1) perror("Removal .");
else printf("Removed. %d\n",err);
}
int main(int argc, char **argv)
{
sem_t *sp;
int retval;
int id, err;
/* Make shared memory segment . */
key_t key=ftok("shmsem",55);
id=shmget(key, SEGMENTSIZE , SEGMENTPERM );
if(id==-1) perror("Creation ");
else printf("Allocated %d\n", id);
/* Attach the segment . */
sp=(sem_t *) shmat (id ,(void *) 0, 0);
/* Initialize the semaphore . */
retval=sem_init(sp,1,2);
if(retval != 0)
{
perror("Couldn’t initialize .");
exit (3);
}
sem_wait(sp);
sharedmemory();
sem_post(sp);
sem_destroy (sp);
err = shmctl(id, IPC_RMID , 0);
if(err==-1) perror("Removal .");
else printf("Removed. %d\n",err);
return 0;
}
Program 2:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<semaphore.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<unistd.h>
#define SEGMENTSIZE sizeof(sem_t)
#define SEGMENTPERM 0666
extern int errno ;
void sharedmemory()
{
char *s;
int err,id;
key_t key=ftok("shm",45);
id=shmget(key, SEGMENTSIZE , SEGMENTPERM );
/* Attach the segment . */
s=shmat(key ,(void*) 0, 0);
printf("Data read from Memory ");
puts(s);
err=shmdt((void*) s);
if(err==-1) perror ("Detachment .");
}
int main(int argc, char **argv )
{
sem_t *sp;
int retval;
int id, err;
key_t key=ftok("shmsem",55);
id=shmget(key, SEGMENTSIZE , SEGMENTPERM );
/* Attach the segment . */
sp=(sem_t *)shmat(id ,(void*) 0, 0);
/* Initialize the semaphore . */
retval=sem_init(sp ,1,1);
if(retval != 0)
{
perror("Couldn’t initialize .");
exit(3);
}
sem_wait(sp);
sharedmemory();
sem_post(sp);
err=shmdt((void*) sp);
if(err==-1) perror ("Detachment .");
return 0;
}