共享名为POSIX的信号量 [英] Share named POSIX semaphores
问题描述
我在理解如何在多个进程之间共享POSIX信号时遇到问题.我正在尝试执行以下操作:
1.生产者初始化一个信号量
2.生产者将10个令牌发布到该信号量,并在此之前睡眠1秒
3.消费者从信号量中获取令牌
当我启动生产者时,出现分段错误(核心已转储).此外,我不确定共享命名信号量的方式是否正确.
生产者:
I have issues understanding how to share a POSIX semaphore among multiple processes. I am trying to do the following:
1. The producer initializes a semaphore
2. The producer posts 10 tokens to the semaphore and sleeps 1 second before doing so
3. The consumer gets a token from the semaphore
When I start my producer, a segmentation fault (core dumped) occurs. Furthermore I am not sure, if my way of sharing the named semaphore is correct.
Producer:
#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#define SEM_NAME "/mutex"
int main () {
sem_t* sem = sem_open(SEM_NAME,O_CREAT,0644,0);
for (int i = 0; i<10; i++) {
sleep(1);
sem_post(sem);
printf("Token was posted! \n");
}
sem_close(sem);
sem_unlink(SEM_NAME);
}
消费者:
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <fcntl.h>
int main () {
sem_t *mutex = sem_open("/mutex",O_CREAT);
for(int i = 0; i<10; i++) {
sem_wait(mutex);
printf("One Token was consumed! %d",(int) getpid());
}
sem_close(mutex);
}
推荐答案
让您的消费者等待:
sem_wait(mutex);
并冲洗每张照片(如果没有打印,可能会在末尾全部冲洗掉):
and flush each print (if not prints may all be flushed at the end):
print("One token consumed\n");
也;请注意从打开处返回的值:
Also; please take care of returned value from open:
if (mutex==SEM_FAILED) exit(1);
和
if (sem==SEM_FAILED) exit(1);
这篇关于共享名为POSIX的信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!