1 year ago
#312692
F.K
shm_open gives segmentation fault when it compiled with -static flag
I am trying to build a shared memory application where I can share data between unrelated processes. In my example, POSIX shm_open call works fine if I use the Dynamic linking while building as below
gcc main.c -o example -lpthread -lrt
But when I build it with static linking using the below command, it builds successfully but throws SIGSEGV while calling shm_open call.
gcc main.c -static -o example -lrt -lpthread
What could be the possible reason for the segmentation fault while calling shm_open.
Here is the example main.c code that I am using:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
#define DATA "/mtxmydata"
struct mydata { int a, b; pthread_mutex_t mtxlock; };
int main()
{
int fd;
unsigned int val;
struct mydata *addr;
pthread_mutexattr_t pshared;
pthread_mutexattr_init(&pshared);
pthread_mutexattr_setpshared(&pshared, PTHREAD_PROCESS_SHARED);
pthread_mutexattr_getpshared(&pshared , &val);
printf(" %d\n", val);
fd = shm_open(DATA, O_CREAT | O_RDWR, 0666);
if (fd == -1) {
perror("shm_open");
exit(1);
}
/* 4k is min shared memory */
if (ftruncate(fd, getpagesize()) == -1) {
perror("ftruncate");
exit(1);
}
addr = (struct mydata *)mmap(NULL, sizeof(struct mydata),
PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
perror("mmap");
exit(1);
}
pthread_mutex_init(&addr->mtxlock, &pshared);
addr->a = 0;
addr->b = 0;
munmap(addr, sizeof(struct mydata));
return 0;
}
c
shared-memory
linkage
librt
0 Answers
Your Answer