1
当我尝试写入内存时出现总线错误(核心转储)。我想在Linux中使用mmap()和open()函数写入二进制文件。我想在二进制文件中将1到100的整数映射到内存,而不是直接写入文件。总线错误与mmap
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#define FILE_SIZE 0x100
int main(int argc,char *argv[])
{
int fd;
void *pmap;
printf("im here");
//fd=open(argv[1],O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
fd=open("numbers.raw",O_RDWR);
if(fd == -1)
{
perror("open");
exit(1);
}
lseek(fd,FILE_SIZE+1,SEEK_SET); //checking the file length
lseek(fd,0,SEEK_SET);//points to start of the file
//create the memory mapping
pmap = mmap(0,FILE_SIZE,PROT_WRITE,MAP_SHARED,fd,0);
if(pmap == MAP_FAILED)
{
perror("mmap") ;
close(fd);
exit(1);
}
close(fd);
for(int i=1;i<=100;i++)
sprintf(pmap,"%d",i);
return 0;
}
我已经增加了FILE_SIZE到0xA00在一个更安全的一面。为了存储二进制数字并推进,我使用了printf(pmap,“%d \ n”,i)。但我仍然得到同样的错误。 –
另外如何在open()命令中指定文件大小 –