本文介绍了与MMAP给总线错误只在一个特定的机器的shm_open的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下简单的程序来创建共享内存。但是,这是给
This is happening only on one virtual machine and I tried the same code in mutiple VM and in every other machine this is working correctly. But only on one machine this issue is happening. Can anyone point me the issue. All my machines are running on 2.6.32-279.el6.x86_64 . Will this be a kernel issue or application issue?
#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);
}
解决方案
You are copying 50 bytes
memcpy((char *)memPtr, "test input.Just copying something\n", 50);
/* BTW: ^ this cast is unneeded */
there are only 36 available, so you are reading beyond the string literal, which is undefined behavior, that's why it works on one machine and fails on another, that's how undefined behavior behaves.
Try
strcpy((char *) memPtr, "Test input. Just copying something\n");
这篇关于与MMAP给总线错误只在一个特定的机器的shm_open的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!