shm_open 在使用 -static 标志编译时给出分段错误
我正在尝试构建一个共享内存应用程序,可以在不相关的进程之间共享数据。在我的示例中,如果我在构建时使用动态链接,POSIX shm_open 调用工作正常,如下所示,
gcc main.c -o example -lpthread -lrt
但是当我使用以下命令使用静态链接构建它时,它构建成功,但在调用 shm_open 调用时抛出 SIGSEGV。
gcc main.c -static -o example -lrt -lpthread
调用 shm_open 时出现分段错误的可能原因是什么。
这是我正在使用的示例 main.c 代码:
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论