c - 你知道为什么这个 C 代码以 "segmentation fault"结尾吗?

标签 c shared-memory semaphore mmap

你知道为什么这段C代码以“segmentation fault”结尾吗?

#include <semaphore.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>


#define NAMESEM "/mysem"

int main(int argc, char* argv) {
 sem_t* sem;
 int fd = shm_open(NAMESEM, O_RDWR|O_CREAT|O_EXCL|O_TRUNC, 0);

 ftruncate(fd, sizeof(sem_t));

 sem = mmap(NULL, sizeof(sem_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

 sem_init(sem, 1, 0);

 sem_wait(sem);

 return 0;
}

我已经关注了此处找到的所有与此相关的帖子,但似乎 sem_init() 生成了段错误,我不知道为什么。我是否在使用指针时犯了一些错误?

最佳答案

考虑在这一行中传递给 shm_open 的标志:

int fd = shm_open(NAMESEM, O_RDWR|O_CREAT|O_EXCL|O_TRUNC, 0);
                                  ^^^^^^^^^^^^^^

这意味着当 NAMESEM 不存在时它会第一次工作。由于 O_EXCL,后续 shm_opens 将失败。这反过来意味着 ftruncatemmap 将失败。问题的要点是这些 IPC 对象在程序终止后仍然存在,直到被明确删除或直到系统重新启动。

O_EXCL

If O_CREAT was also specified, and a shared memory object with the given name already exists, return an error.

但您代码中的真正问题是您没有检查这些函数的返回值。一个简单的 perror 会立即指出问题。

关于c - 你知道为什么这个 C 代码以 "segmentation fault"结尾吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673154/

相关文章:

c - 具有共享内存和信号量的多个灵活阵列成员或 VLA

c - switch 语句的更好替代方案

c - 使用C语言从Arduino串口获取数据时出错

dll - 在多个进程中加载​​相同的 dll 实例

共享内存实现上的 C++ 内存池 : Is this method of allocation and deallocation correct?

c - 如何在linux中引发因EINTR而失败的semop调用?

c - scanf 阻止程序运行

c - 在 char* 中存储不同的结构?

java - C 或 Java 的非玩具软件事务内存

c - C 中的信号量示例