【问题标题】:Bus Error when writing to Shared Memory写入共享内存时出现总线错误
【发布时间】:2024-01-29 06:20:01
【问题描述】:

我正在尝试在 Linux 系统上使用 POSIX 共享内存。但是当我尝试将数据复制到它时,我得到一个总线错误。代码如下:

#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

void main ()
{
    char *s = "a";
    //<!--make file descripter-->
    int fd = shm_open (s, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
    if (fd == -1)
    {
        perror ("shm open:");
        printf ("error\n");
        shm_unlink (s);
        exit (1);
    }

    //<!--memory allocation-->
    char *str = (char *)mmap (NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (str == MAP_FAILED)
    {
        perror ("mmap");
        exit (1);
    }

    *(str + 1) = 'a';   
    //<!--memory deallocation-->
    munmap (str, 10);
    //<!--unlink shared memory-->
    shm_unlink (s);
}

是什么导致它崩溃?

【问题讨论】:

  • 不清楚错误在哪里。你能粘贴错误吗?
  • main() 必须返回 int - 我猜你没有用 gcc -Wall 编译?一定要打开您的诊断报告 - 越早越好! (它也可能会捕捉到您将字符串文字分配给s
  • 另外,不要转换 mmap() 的结果 - 原因与我们不转换 malloc() 的结果相同:Do I cast the result of malloc?

标签: linux posix shared-memory bus-error


【解决方案1】:

您正在访问超出映射文件末尾的内存。您需要扩展文件的大小以获取空间。在shm_open()之后,添加:

int size = 10; // bytes
int rc = ftruncate(fd, size);
if(rc==-1){ ...; exit(1); }

【讨论】:

    最近更新 更多