我试图使用下面的代码测试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;
   }
}发布于 2018-10-08 09:38:26
在创建/打开信号量之前使用sem_unlink()解决了我的问题。
谢谢
以下是代码:
int main() 
{ 
    sem_unlink(SemaphoreName);
    SysInit();
    while(1)
    {
    CriticalSection();
    }
    return 0; 
} https://stackoverflow.com/questions/52698157
复制相似问题