Ham*_*148 4 c mmap shared-memory bus-error
当我上学期第一次做这个项目时,代码运行得很好。现在,当写入要在进程之间共享的映射内存时,我收到总线错误,并且我不确定为什么它不再工作。
Account_Info *mapData()
{
int fd;
//open/create file with read and write permission and check return value
if ((fd = open("accounts", O_RDWR|O_CREAT, 0644)) == -1)
{
perror("Unable to open account list file.");
exit(0);
}
//map data to be shared with different processes
Account_Info *accounts = mmap((void*)0, (size_t) 100*(sizeof(Account_Info)), PROT_WRITE,
MAP_SHARED, fd, 0);
int count= 0;
//loop to initialize values of Account_Info struct
while (count != 20)
{
//bus error occurs here
accounts[count].CurrBalance= 0;
accounts[count].flag = 0;
int i = 0;
while (i != 100)
{
//place NULL terminator into each element of AccName
accounts[count].AccName[i]= '\0';
i++;
}
count++;
}
close(fd);
return accounts;
}
Run Code Online (Sandbox Code Playgroud)
使用 mmap 进行 SIGBUS 的记录原因是
尝试访问缓冲区中与文件不对应的部分(例如,超出文件末尾,包括另一个进程截断了文件的情况)。
我的猜测是该accounts文件不存在,因此创建open了O_CREAT它。但它的大小为零,因此任何通过映射读取或写入的尝试都会出错。您需要用足够的零(或其他内容)填充文件以覆盖映射,例如使用ftruncate.