Search code examples
linuxposixsemaphore

POSIX Semaphore sem_wait () is blocking infinitely


I am trying to test the POSIX semaphore by using following code but the problem sem_wait function is blocking the program infinitely and once it is working then i want to try the same code from multiple processes. Please let me know if anything is missing in the code.

Here is the code:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <fcntl.h> 
#include <sys/shm.h> 
#include <sys/stat.h> 
#include <sys/mman.h>
#include <semaphore.h>

void SysInit(void);
void CriticalSection(void);

const char* name = "OS"; 
const char* SemaphoreName = "ShareObject";
sem_t *Sem_SharedMemory_t;

int main() 
{ 
    SysInit();
    while(1)
    {
        CriticalSection();
    }
    return 0; 
} 

void SysInit(void)
{
    printf("-----------------In System Init Section_1--------------------\n");

    if ((Sem_SharedMemory_t = sem_open(SemaphoreName, O_CREAT, 0644, 1)) < 0)  //Opens semaphore
    {
        perror("sem_open");
        exit(1);
    }
    printf("-----------------Semaphore Id:%d--------------------\n",Sem_SharedMemory_t);
}

void CriticalSection(void)
{
   int i;
   printf("Before Entering Critical Section:%d\n",Sem_SharedMemory_t);
   if(sem_wait(Sem_SharedMemory_t) < 0)  //Blocking section 
   {
       perror("sem_wait");
       return;
   }
   printf("Before Loop\n");
   for(i=0;i<3;i++)
   {
       printf("In Critical Section_1, Count i:%d\n",i);
       sleep(1);
   }
   if(sem_post(Sem_SharedMemory_t) < 0)
   {
     perror("sem_wait");
         return;
   }
}

Solution

  • Using sem_unlink() before Creating/opening the semaphore has solved my problem.

    Thank you

    Here is the code:

    int main() 
    { 
        sem_unlink(SemaphoreName);
        SysInit();
        while(1)
        {
        CriticalSection();
        }
        return 0; 
    }