【问题标题】:Semaphore is acquired only by one process信号量仅由一个进程获取
【发布时间】:2019-05-09 16:58:31
【问题描述】:

我正在尝试为 POSIX 标准重构我的 C 代码。显然我遇到了死锁,这归结为这个简单的代码。信号量应该在两个进程之间共享,但不幸的是它由创建它的进程所有。

创作者

sem_t * mutex;

  if ((mutex = sem_open (key_trucker, O_CREAT, 0644, 1)) == SEM_FAILED) {
       perror ("sem_open"); exit (1);
    }

    int val;
    sem_getvalue(mutex,&val);

    if(val == 0 ){
      sem_post(mutex);
    }

  time_t currtime;
  while(1){
    sem_wait(mutex);
    time(&currtime);
    sleep(1);
    printf("%s",ctime(&currtime) );
    sem_post(mutex);
  }

共享信号量的进程

sem_t * mutex;

  if ((mutex = sem_open (key_trucker, 0 )) == SEM_FAILED) {
       perror ("sem_open"); exit (1);
        }

  time_t currtime;
  while(1){
    sem_wait(mutex);
    time(&currtime);
    printf("%s",ctime(&currtime) );
    sleep(1);
    sem_post(mutex);
  }

【问题讨论】:

    标签: c semaphore


    【解决方案1】:

    要在进程之间共享的信号量必须是“命名”信号量。这样的名称以“\”开头。信号量最终也需要被销毁,否则第二次进程调用sem_open() 它将失败并将'errno'设置为EXIST(或类似)所以代码还需要(在注意到调用失败后)检查errno的值

    【讨论】:

    • 共享内存不能替代命名信号量吗?
    • @rcgldr,共享内存将是一个可行的选择,但是,发布的代码没有使用共享内存
    猜你喜欢
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2016-06-21
    • 2016-06-21
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    相关资源
    最近更新 更多