关于多线程:命名 POSIX 信号量的问题

Issues with named POSIX semaphore

我正在尝试使用 POSIX 命名信号量来确保我的可执行文件只有一个实例可以运行。但是我遇到了麻烦;信号量的值始终为 0,因此它总是阻塞。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <semaphore.h>  /* required for semaphores */
#include <stdio.h>
#include <unistd.h>     /* usleep */
#include <fcntl.h>      // O_EXCL
#include
#include <stdlib.h>     /* exit, EXIT_FAILURE */


int main(int argc, char *argv[])
{
  int ret;
  int i;
  sem_t* semaphore;

  semaphore = sem_open("/mysemaphore", O_EXCL, 0777 /*0644*/, 2);
  printf("sem_open returned %p at line %u\
", semaphore, __LINE__);

  // if it exists, open with"open", and parameters will be ignored (therefore given as 0)
  if(!semaphore)
  {
    semaphore = sem_open("/mysemaphore", O_CREAT, 0, 0);
    printf("sem_open returned %p at line %u\
", semaphore, __LINE__);
  }

  // either of the above calls should have given us a valid semaphore
  assert(semaphore);

  // read its value time and again
  ret = sem_getvalue(semaphore, &i);
  printf("sem_getvalue returned %i at line %u, value is %i\
", ret, __LINE__, i);

// ....

输出:

1
2
sem_open returned 0x8003a4e0 at line 36
sem_getvalue returned 0 at line 50, value is 0

平台:Cygwin 1.7.33-2

使用以下命令构建:

1
gcc Main.c -o Main -lpthread

非常感谢您的帮助!


使用sem_post(semaphore)增加,sem_wait(semaphore)减少。

另外,当使用 O_CREAT 时,模式和值应该指定为有用的东西:

1
semaphore = sem_open("/mysemaphore", O_CREAT, 0777, 0);