了解posix进程间信号量 [英] Understanding the posix interprocess semaphore
问题描述
根据我的理解,信号量应该可以在相关进程中使用,而不必放置在共享内存中.如果是这样,为什么以下代码会死锁?
According to my understanding, a semaphore should be usable across related processes without it being placed in shared memory. If so, why does the following code deadlock?
#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不会有任何好处.我想念什么吗?
When I run this on Gentoo/Ubuntu Linux, the parent hangs. Apparently, it did not receive the post by child. Uncommenting sem_destroy won't do any good. Am I missing something?
更新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);
}
谢谢, 尼罗什.
推荐答案
如果pshared不为零,则信号在进程之间共享,
和应位于共享内存区域.
If pshared is nonzero, then the semaphore is shared between processes,
and should be located in a region of shared memory. 由于fork(2)创建的子项继承了其父项的内存
映射,它也可以访问信号量. Since a child created by fork(2) inherits its parent's memory
mappings, it can also access the semaphore. 是,但它仍必须位于共享区域中.否则,只需使用通常的 CoW 复制内存即可. Yes, but it still has to be in a shared region. Otherwise the memory simply gets copied with the usual CoW and that's that. 您可以通过至少两种方式解决此问题: You can solve this in at least two ways: 这篇关于了解posix进程间信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
sem_open("my_sem", ...)
shm_open
和mmap
创建共享区域
sem_open("my_sem", ...)
shm_open
and mmap
to create a shared region