段故障设置信号量函数

Segmentation fault setup semaphore function

我在 shared_memory.c 文件中声明了我的函数。其中一个函数是 setupSemaphoreRead()。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <pthread.h> 
#include <sys/sem.h>
#include <semaphore.h>
#include <fcntl.h>

#include "shared_memory.h"

//more code...
 
int setupSemaphoreRead(){
    sem_unlink(SEM_CONSUMER_FNAME);
    sem_unlink(SEM_PRODUCER_FNAME);
    
    sem_t *sem_prod = sem_open (SEM_PRODUCER_FNAME, O_CREAT | O_EXCL, 0666, 0);
        if (sem_prod == SEM_FAILED) {
            perror("sem_open/producer");
            return -1;
        }
    sem_t *sem_cons = sem_open (SEM_CONSUMER_FNAME, O_CREAT | O_EXCL, 0666, 1);
        if (sem_cons == SEM_FAILED) {
            perror("sem_open/consumer");
            return -1;
        }

    return 1;
}
    //more code...

我得到了在我的头文件中声明的签名

int setupSemaphoreRead();
//filenames for two semaphores
#define SEM_PRODUCER_FNAME "myproducer"
#define SEM_CONSUMER_FNAME "myconsumer"

在我的主要阅读程序中,我尝试以休闲方式使用该功能:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <pthread.h> 
#include <fcntl.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>



#include "shared_memory.h"
...
    sem_t *sem_cons;
    sem_t *sem_prod;
    setupSemaphoreRead();
...

编译代码时我没有得到任何错误,但是在执行时我得到了分段错误(核心转储)

你有

sem_t *sem_prod

函数内部和main内部。换句话说 - 它们是不同的变量,即 main 中的变量不会被函数更新。

setupSemaphoreRead() 分配给 sem_t * 局部变量。当它 returns 时,这些变量超出范围。它无法访问其他范围内的同名变量。您需要更多地研究变量作用域在 C 中是如何工作的。一种典型的方法是让一个函数接受双指针参数,例如:

int setupSemaphoreRead(sem_t** sem_cons, sem_t** sem_prod) {
    *sem_cons = ...
    ..

并像这样使用它:

sem_t* sem_cons;
sem_t* sem_prod;
int ret = setupSempahoreRead(&sem_cons, &sem_prod);
// Make sure to check the value of ret