c – 理解posix进程间信号量

根据我的理解,信号量应该可以在相关进程中使用,而不必放在共享内存中.如果是这样,为什么以下代码死锁?

#include <iostream>
#include <semaphore.h>
#include <sys/wait.h>

using namespace std;

static int MAX = 100;

int main(int argc, char* argv[]) {
  int retval;
  sem_t mutex;

  cout << sem_init(&mutex, 1, 0) << endl;

  pid_t pid = fork();

  if (0 == pid) {
    //     sem_wait(&mutex);
    cout << endl;
    for (int i = 0; i < MAX; i++) {
      cout << i << ",";
    }
    cout << endl;
    sem_post(&mutex);

  } else if(pid > 0) {
    sem_wait(&mutex);
    cout << endl;
    for (int i = 0; i < MAX; i++) {
      cout << i << ",";
    }
    cout << endl;
    //     sem_post(&mutex);
    wait(&retval);

  } else {
    cerr << "fork error" << endl;
    return 1;
  }

//   sem_destroy(&mutex);

  return 0;
}

当我在Gentoo / Ubuntu Linux上运行它时,父级挂起.显然,它没有收到孩子的帖子.取消注释sem_destroy不会有任何好处.我错过了什么吗?

更新1:
这段代码有效

mutex = (sem_t *) mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, 0, 0);
if (!mutex) {
  perror("out of memory\n");
  exit(1);
}

谢谢,
Nilesh制作.

解决方法:

the manual page中的措辞有点含糊不清.

If pshared is nonzero, then the semaphore is shared between processes,
and should be located in a region of shared memory.

Since a child created by fork(2) inherits its parent’s memory
mappings, it can also access the semaphore.

是的,但它仍然必须在共享区域.否则,内存只会被通常的CoW复制,就是这样.

您可以通过至少两种方式解决此问题:

>使用sem_open(“my_sem”,…)
>使用shm_open和mmap创建共享区域

上一篇:ubuntu:sem_timedwait没有醒来(C)


下一篇:使用java信号量解决读者/写作者