Home > OS >  Segmentation fault setup semaphore function
Segmentation fault setup semaphore function

Time:10-15

I got the shared_memory.c file where I'm declaring my functions. One of the functions will be 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...

I got the signature declared at my header file

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

In my main read program I'm trying to use the function in the fallowing way:

#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();
...

I don't get any error when compiling the code, but when executing I got Segmentation fault (core dumped)

CodePudding user response:

setupSemaphoreRead() assigns to sem_t * local variables. When it returns those variables are out of scope. It has no access to variables of the same name in the other scope. You need to study more how variable scopes work in C. A typical way to do what you're trying to do is have a function accept double-pointer arguments like:

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

and use it like:

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

CodePudding user response:

You have

sem_t *sem_prod

both inside the function and inside main. In other words - they are different variables, i.e. the variables in main are not updated by the function.

  • Related