I have a problem with a semaphore in my code.
This is a struct that I built:
struct PipeShm
{
// doesn't matter
sem_t *mutex;
int init;
// more fields
};
Here I initialize the struct:
struct PipeShm myPipe ;
myPipe.mutex = NULL;
myPipe.init = 0;
And I use an initialization method:
int initMethod()
{
if (!myPipe.init)
{
myPipe.mutex = mmap (NULL, sizeof *myPipe.mutex, PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (!sem_init (myPipe.mutex, 1, 0))
{
myPipe.init = TRUE;
}
else
perror ("initMethod");
}
return 1;
}
This is a simple main that uses the above :
int main()
{
int spd, pid, rb;
char buff[4096];
shm_pipe_init();
fork();
// more code goes here
return 0;
}
In the line fork(); (please correct me if I’m wrong) the 2 processes would
have the two different semaphores, right?
If so, I want to make the a global semaphore. Is that possible?
Due to problems of synchronization in my code, I suspect that the main reason is
a double semaphore for each created process.
Your code to initialize the semaphore appears to be correct, so you will have to look elsewhere for your synchronization problems. Below is a test program that illustrates working behavior for your code:
I think you would already know, but just in case, a semaphore is not really a mutex. You can think of a mutex as a semaphore that is initialized to a post value of
1. But, a semaphore does not prevent multiple simultaneous posts. If you have spurious posts to the semaphore, this will allow more than one thread to go into the critical section.