gpt4 book ai didi

c - 写入映射数据时出现总线错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:20:56 24 4
gpt4 key购买 nike

当我上学期第一次做这个项目时,代码运行良好。现在,在写入要在进程之间共享的映射内存时出现总线错误,我不确定为什么它不再工作了。

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;
}

最佳答案

SIGBUS 与 mmap 的记录原因是

Attempted access to a portion of the buffer that does not correspond to the file (for example, beyond the end of the file, including the case where another process has truncated the file).

我的猜测是 accounts 文件不存在,所以用 O_CREAT open 创建了它。但它的大小为零,因此任何通过映射读取或写入的尝试都会出错。您需要用足够的零(或其他东西)填充文件以覆盖映射,例如使用 ftruncate

关于c - 写入映射数据时出现总线错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39939033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com