Share named POSIX semaphores

别等时光非礼了梦想. 提交于 2019-12-24 20:40:11

问题


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);
}

Consumer:

#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);
}

回答1:


Make your consumer wait :

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);

and

if (sem==SEM_FAILED) exit(1);


来源:https://stackoverflow.com/questions/50702902/share-named-posix-semaphores

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!