首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >POSIX信号量sem_wait ()无限阻塞

POSIX信号量sem_wait ()无限阻塞
EN

Stack Overflow用户
提问于 2018-10-08 08:23:26
回答 1查看 327关注 0票数 2

我试图使用下面的代码测试POSIX信号量,但是问题sem_wait函数无止境地阻塞了程序,一旦程序正常工作,我想从多个进程尝试相同的代码。如果代码中有遗漏,请告诉我。

以下是代码:

代码语言:javascript
运行
复制
#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;
   }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-08 09:38:26

在创建/打开信号量之前使用sem_unlink()解决了我的问题。

谢谢

以下是代码:

代码语言:javascript
运行
复制
int main() 
{ 
    sem_unlink(SemaphoreName);
    SysInit();
    while(1)
    {
    CriticalSection();
    }
    return 0; 
} 
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52698157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档