我尝试将共享内存与shm_open和mmap一起使用。但是,每当我尝试写入该内存时,都会出现总线错误。下面给出了极简示例代码。这里有什么问题,如何解决?
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// compile with -lrt
char fname[64];
int fd;
int main()
{
int * sm;
sprintf( fname, "%d_%u", 4, 4 );
if ((fd = shm_open(fname, O_CREAT | O_RDWR, 0777)) == -1)
{
perror(NULL);
return 0;
}
sm = (int*)mmap(0, (size_t)4096, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED,
fd, 0);
printf( "Now trying to see if it works!\n" );
sm[0] = 42;
printf( "%d, %d!\n", sm[0], sm[1] );
return 0;
}
我得到的输出如下
Now trying to see if it works!
Bus error