POSIX 信号量 sem_wait () 无限阻塞

POSIX Semaphore sem_wait () is blocking infinitely

我正在尝试使用以下代码测试 POSIX 信号量,但是 sem_wait 函数的问题是无限地阻止程序,一旦它工作,我想尝试来自多个相同的代码过程。如果代码中缺少任何内容,请告诉我。

代码如下:

#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;
   }
}

在 Creating/opening 信号量之前使用 sem_unlink() 已经解决了我的问题。

谢谢

代码如下:

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