我有以下创建共享内存的简单程序。但这是给
Bus error (core dumped)
这只发生在一台虚拟机上,我在多台虚拟机上尝试了相同的代码,并且在其他每台机器上都正常工作。但仅在一台机器上会出现此问题。谁能指出我的问题。我所有的机器都在 2.6.32-279.el6.x86_64 上运行。这是内核问题还是应用程序问题?
#include<stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
const char *shpath="/shm_path_for_data";
void *memPtr;
shm_unlink(shpath);
int fd=0;
fd = shm_open(shpath, O_RDWR|O_CREAT|O_EXCL, 0777);
if(fd<0) {
printf("shm_open failed\n");
return 1;
}
if((ftruncate(fd, getpagesize())) <0) {
printf("Ftruncate failed\n");
return 1;
}
memPtr = mmap(NULL, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if(memPtr == MAP_FAILED) {
return 1;
}
strcpy((char *)memPtr, "test input.Just copying something\n");
printf("mapped out: %s\n", (char *)memPtr);
}
最佳答案
你正在复制 50 个字节
memcpy((char *)memPtr, "test input.Just copying something\n", 50);
/* BTW: ^ this cast is unneeded */
只有 36 个可用,所以您正在阅读字符串文字之外的内容,这是未定义的行为,这就是为什么它在一台机器上工作而在另一台机器上失败的原因,这就是未定义行为的行为方式。
尝试
strcpy((char *) memPtr, "Test input. Just copying something\n");
关于c - 带有 mmap 的 shm_open 仅在一台特定机器上给出总线错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31056508/