I try to write a process for data acqusition from incremental encoder on Raspberry Pi in C. Unfortunately, I have encountered an issue with shm_open() function during operation - it gives me segmentation fault. Despite segmentation fault error, name of the shared memory fragment is shown in /dev/shm catalogue after program crash. What could be the cause of such behaviour? I tested program on Raspbian Buster and Ubuntu 20.04 - the behaviour on both systems is the same.
Code for encoder process:
#include <signal.h>
#include <stdlib.h>
#include <time.h>
#include "stdio.h"
#include <string.h>
#include <unistd.h>
#include "encbuffer.h"
#define ENNAME "/test"
int mode = 4;
int pulses_amount_gpio_4 = 0;
int encoder_buffer_fd = 0;
double local_angle = 1;
struct encoder_buffer *enc_buffer;
void* shm_enc_buffer;
void Handler(int signo)
{
mode = 2;
}
int main(void)
{
// the issue is here
encoder_buffer_fd = shm_open(ENNAME, O_CREAT|O_RDWR|O_TRUNC, 0666);
if(encoder_buffer_fd < 0)
{
perror("shm_open()");
return 1;
}
printf("passed buffer opening");
ftruncate(encoder_buffer_fd, sizeof(struct encoder_buffer));
shm_enc_buffer = mmap(0, sizeof(struct encoder_buffer), PROT_WRITE|PROT_READ, MAP_SHARED, encoder_buffer_fd, 0);
// Exception handling:ctrl + c
signal(SIGINT, Handler);
if(sem_init(&(enc_buffer->semaphore), 1, 1) < 0)
{
return 3;
}
while(mode != 2)
{
/*printf("Angle: %f\n", local_angle);
sleep(1);*/
}
munmap(0, sizeof(struct encoder_buffer));
shm_unlink(ENNAME);
return 0;
}
Code for encoder buffer:
#ifndef _ENCBUFFER_H_
#define _ENCBUFFER_H_
#include <stdlib.h>
#include <signal.h>
#include "stdio.h"
#include <semaphore.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/mman.h>
#include <assert.h>
#include <sys/stat.h>
#include <fcntl.h>
struct encoder_buffer {
double angle;
double previous_angle;
sem_t semaphore;
};
#endif
Makefile:
CC = gcc
MSG = -g -O0 -Wall -I. -lrt -pthread
CFLAGS += $(MSG)
DEPS = encbuffer.h
OBJ = anglecollect.o
%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)
angle: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS)
` Tried running on both Raspberry Pi 4 with Raspbian Buster and normal PC with Ubuntu 20.04 - unfortunately, without success. I also tried adding extra flags to makefile(details of the solution discussed in this topic: shm_open gives segmentation fault when it compiled with -static flag), unfortunately without success. GCC version on Ubuntu is 9.4.0. GCC version on Raspbian Buster is 10.2.1.