【发布时间】: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